Thursday, May 19, 2011

WebView - Part 2 Accesing Files on Device and in APK itself

Accessing files in Android device using WebView

For using WebView you must have the permissions to access INTERNET and to request permission to access INTERNET just add the following line in your application's manifest just under </application> tag  i.e. make it a child of manifest tag.

     <uses-permission android:name="android.permission.INTERNET"/>

Create the following HTML either programmatically using code in String format or create the file and save that in /res/value/string.xml and name it as <somename>
            <html>
          <head><title>Test File Loading</title></head>
          <body>
Here we are loading the image file in HTML
To display:<br>
<img height=”100” width=”100” src=file:///yourimagefilepath></img>
          </body>
     </html>

To reference the file in <img> tag, you have to use the file URI pointing to the location where the file is saved.

Here’s the Java code to load this HTML into a WebKit component:
            WebView web = (WebView)findViewById(R.id.web_view);
            final String mimeType = “text/html”;
     final String encoding = “UTF-8”;
String htmldata =
          getResources().getString(R.string.<somename>);
     if(htmldata != null){
          web.loadData(html,
                        mimeType,
                        encoding);
     }
else{
web.loadData(“<html><body>Failed</body></html>”
     ,mimeType, encoding);
}

Now, you should be able to see image in your WebView

Accessing resources bundled with APK
Create the following HTML either programmatically using code in String format or create the file and save that in /res/value/string.xml and name it as <somename>
            <html>
          <head><title>Test File Loading</title></head>
          <body>
Here we are loading the image file in HTML
To display:<br>
<img height=”100” width=”100” src=file:///android_asset/imagename></img>
          </body>
     </html>
To reference the file in <img> tag, you have to use the file URI pointing to the /android_asset/imagename.


Here’s the Java code to load this HTML into a WebKit component:
            WebView web = (WebView)findViewById(R.id.web_view);
            final String mimeType = “text/html”;
     final String encoding = “UTF-8”;
String htmldata =
          getResources().getString(R.string.<somename>);
     if(htmldata != null){
          web.loadData(html,
                        mimeType,
                        encoding);
     }
else{
web.loadData(“<html><body>Failed</body></html>”
     ,mimeType, encoding);
}

Now, you should be able to see image in your WebView.

<<WebView – Part 1 Capabilities and Limitations  

WebView - Part 3 How to customize WebView?>>


Cheers!!
Vivek Jain
Hello Everyone, I came across an application which allowed me to produce nice effects on Images that are in my phone and Images that I take from my phones camera, its available here, 

No comments:

Post a Comment