SPillai
SPillai

Reputation: 187

Android - Set a Local Image to an img element in WebView

I am passing a local file through Javascript to set an img source and I cannot get it working. The javascript to set the path is

<img src='" + the_payload.image + "' width='" + (cellWidth()-20) + "' />

The String that I am sending is the complete file path:

file:///mnt/sdcard/Android/data/com.newvisioninteractive.android.myapp/files/c87eba4a-5349-4a55-baec-cc573a5f7571-thumb.png

I saw a post about ContentProviders and ParcelFileDescriptors but could not get that to work either.

This is for a Calendar View that displays images on certain days. It works fine when I pass in a static image, just not a local one.

Also, I have set

    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);

Do I need to set any other Permissions?

Upvotes: 0

Views: 3058

Answers (2)

SPillai
SPillai

Reputation: 187

The solution is in extending the ContentProvider class and Overriding the openFile(Uri, String) method

package com.packagename.provider;
public class MyProvider extends ContentProvider { 
     @Override
     public ParcelFileDescriptor openFile(Uri uri, String mode){
        URI fileURI = URI.create( "file://" + uri.getPath() );
        File file = new File( fileURI );

        ParcelFileDescriptor parcel = null;
        try {
            parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        } catch (FileNotFoundException e) {
            Log.e( TAG, "Error finding: " + fileURI + "\n" + e.toString() );
        }

        return parcel;
     }
}

Then in your AndroidManifest.xml file include

 <provider
        android:name=".provider.MyProvider"
        android:authorities="com.packagename" />

You can then access your files which would normally be

 file://sdcard/Android/data/com.packagename/image.jpg

by using

 content://com.packagename/sdcard/Android/data/com.packagename/image.jpg

So essentially replace file:// with content://com.packagename

Upvotes: 1

SquiresSquire
SquiresSquire

Reputation: 2414

try using file:///android_assets/image.png and place images in the android assets

Upvotes: 0

Related Questions