Paradiesstaub
Paradiesstaub

Reputation: 2660

WebView load images asynchronously from Database

I would like to load images referenced in HTML asynchronously from my local Database.

Right now all I can do is to replace the abc.jpg part of <img src="abc.jpg"> by data:image/jpg;base64, img_base64_string>, but this has to be done before the HTML get's rendered. I would like to show the HTML page as fast as possible and then load the images.

Upvotes: 0

Views: 1178

Answers (1)

Paradiesstaub
Paradiesstaub

Reputation: 2660

The trick is to create a ParcelFileDescriptor.createPipe() to copy the database file through streams to the WebView.

LocalImageContentProvider.java

public class LocalImageContentProvider extends ContentProvider {

    private static final String AUTHORITY = "com.example.local.provider";
    public static final Uri CONTENT_URI = Uri.parse("content://"+ AUTHORITY +"/image");

    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) {
        String filename = uri.getLastPathSegment();

        // http://developer.android.com/reference/android/os/ParcelFileDescriptor.html#createPipe%28%29     
        // [0] is the reader, [1] is the writer
        ParcelFileDescriptor[] pipe = null;

        try {
            pipe = ParcelFileDescriptor.createPipe();

            // copy DB file through pipe to WebView
            new Thread(new PipeRunnable(
                    getInputStreamFromDbFile(filename),
                    new AutoCloseOutputStream(pipe[1])) )
            .start();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return (pipe[0]);
    }
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" >

    <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="19"/>

    <application>

        <!-- 'activity -->

        <provider android:exported="false"
            android:name=".provider.LocalImageContentProvider"
            android:authorities="com.example.local.provider"
        />

    </application>

</manifest>

To load images in the WebView use the ContentProvider URI + "/image.jpg":
<img src="content://com.example.local.provider/image/29.jpg"></img>

Upvotes: 1

Related Questions