Tuesday, 8 November 2011

WebView with zoom controls, image from SDCARD

The Problem:
When I'm trying to load an image (tried both gif and png) from my assets directory, into a webview.
In my assets folder, I have an image called myImage.gif
Here's my wrong code:

  1. WebView data = (WebView) findViewById(R.id.data)
  2. data.loadData("<IMG HEIGHT=\"42px\" WIDTH=\"42px\" SRC=\"file:///android_assets/myImage.gif\" />", "text/html",  "UTF-8");

All that happens when I try it, is that I get a blank screen with a
empty 42px/42px box.
In logcat, I see the message:
03-30 00:21:14.398: DEBUG/WebCore(214): Console: Not allowed to load
local resource: file:///android_assets/myImage.gif line: 0 source:

The Solution:
Even though, I'm going to load the image file from the filesystem (SDCARD or Phone Storage), instead of Assets folder, I've found a solution for this, and you don't even have to care about ContentProviders... (Which is also a good solution, but this is much easier & quicker in this case.)
The key is WebView's loadDataWithBaseURL method, but let's see an example:
  1. /* Using WebView to display the full-screen image */
  2. WebView full = (WebView)findViewById(R.id.webview);
  3. /* Set up the Zoom controls */
  4. FrameLayout mContentView = (FrameLayout) getWindow().
  5. getDecorView().findViewById(android.R.id.content);
  6. final View zoom = this.full.getZoomControls();
  7. mContentView.addView(zoom, ZOOM_PARAMS);
  8. zoom.setVisibility(View.VISIBLE);
  9. /* Create a new Html that contains the full-screen image */
  10. String html = new String();
  11. html = ("<html><center&gt;<img src=\""+fileName+"\"></html>" );
  12.        
  13. /* Finally, display the content using WebView */
  14. full.loadDataWithBaseURL("file:///sdcard/data/data/com.youproject.example/",
  15.                                                         html,
  16.                                                         "text/html",
  17.                                                         "utf-8",
  18.                                                         "");

1 comment:

  1. Follow this link also for better understanind web views in android

    http://www.taiic.com/2011/03/12/webview-template-for-android-sdk/

    ReplyDelete