Android WebKit Inconsistency

Apologize for the title. It’s not a big deal.

Really.

I have experienced a little (but annoying, at the same time) problem with the Android’s WebKit. There will be a time when you want to render images using WebView object inside your application to support pinch zoom (in and out), download, and store it in your own library. The image itself typically simple. Anything with you-already-knew extensions such as .jpg, .jpeg, .gif, .bmp, and so on.

So, I first start with these codes:

WebView webView = new WebView(this);

webview.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);

After all those setup, it’s the time to load the image using its URL.

webView.loadUrl(imageUrl);

Strange thing start happening here. If your imageUrl is something like this,

http://www.somedomain.com/images/photo.jpg

your webView will show blank page. Nothing rendered. But if you have this,

http://www.somedomain.com/images/photo.jpeg

everything is fine. The image will sit there after a while. So, what’s the problem?

I’ll try to override the onProgressChanged() method to check the progress.

webView.setWebChromeClient(new WebChromeClient() {

@Override
public void onProgressChanged(WebView view, int newProgress) {
        // track the newProgress, from 0 to 100.
    }
}


The progress indeed reach 100 but still, I got the blank page.

I try to render it using the Android’s native browser and I surprised that the browser downloading the image immediately instead of rendering it!

Realize with the situation above, I changed the code so instead of rendering it directly via the url, the browser rendering it via the HTML image tag with Content-Type set to "text/html".

String imgSrcHtml = "<img src='" + imageUrl + "'>";
webView.loadData(imgSrcHtml, "text/html", "utf-8");

and the problem solved.

Also read...

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.