Android tip #1 ContentProvider , Accessing local file system from WebView / showing image in webview using content://
ok, this was a tough one.
First be informed that this is something Google (Android people) are trying to prevent i.e. letting browser (WebView) have access to the local file system. In earlier releases of SDK you could access local files using ‘file://’ but it is stopped now. Then there was an option where you can provide a WebViewClient and implement shouldOverrideUrlLoading to make it work. This was also removed.
The way to make it work now is by implementing your own ContentProvider, there is lot of discussion and documentation on implementing ContentProvider but all that is completely redundant (not needed). The solution is very simple, create your own ContentProvider and only override
<br /> public android.os.ParcelFileDescriptor openFile(android.net.Uri uri, java.lang.String mode) throws java.io.FileNotFoundException<br />
Rest of the code in ContentProvder is not needed for this problem.
Declare your Content Provider in AndroidManifest.xml
</p> <provider android:name="MyDataContentProvider" android:authorities="com.techjini" />
Create your ContentProvider and implement openFile
All you have to do is get real path from uri, open it and return the descriptor
<br /> URI uri = URI.create(“file:///data/data/com.techjini/files/myImage.jpeg”);<br /> File file = new File(uri);<br /> ParcelFileDescriptor parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);<br /> return parcel;<br />
(You need this step only if file is not already present on the device/sdcard)
Save your content to the file. Following is an example to store a Bitmap
<br /> FileOutputStream fos = openFileOutput(“myImage.jpeg”, Activity.MODE_WORLD_WRITEABLE);<br /> imageView.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, fos);</p> <p>fos.flush();<br /> fos.close();<br />
You can find out where your image is stored using
<br /> System.out.println(getFilesDir().getAbsolutePath());<br />
Access the file in WebView
<br /> myWebView.loadUrl(“content://com.techjini/myImage.jpeg”);<br /> //com.techjini is what you mentioned in ‘android:authorities’ in your AndroidManifest.xml<br />