I\'m trying to load/reference images from the app\'s assets folder from within a HTML page in a WebView. Unlike in most of the examples the HTML page itself is not located i
OK, thanks to mufumbo's answer I now found a working hack to mix local assets in remotely loaded HTML pages. Pages loaded using the WebView's loadUrl()
method do not load images linked with file:///android_asset/... As a workaround you can fetch the HTML page using org.apache.http.client.methods.HttpGet.HttpGet()
and then pass it to the WebView with loadDataWithBaseURL()
. In this case the WebView will load resources linked with file:///android_asset/ as well as images and scripts via HTTP. Here's my customized webview code:
public class CustomWebView extends WebView {
private String mURL;
public void loadUrlWithAssets(final String url) {
// copy url to member to allow inner classes accessing it
mURL = url;
new Thread(new Runnable() {
public void run() {
String html;
try {
html = NetUtil.httpGETResponse(mURL);
// replace some file paths in html with file:///android_asset/...
loadDataWithBaseURL(mURL, html, "text/html", "UTF-8", "");
}
catch (IOException e) {
Log.e("CustomWebView.loadUrlWithAssets", "IOException", e);
}
}
}).start();
}
}
Please note that the whole http fetching is wrapped in the home-grown utility class NetUtil
.
With this class it's possible to render HTML pages from a webserver and have some static resources like images or stylesheets loaded from the app's asset folder in order to improve loading speed and to save bandwidth.
This is how I do on the java part:
String myHTML = "< img src=\"file:///android_asset/myimage.jpg\""; myWebView.loadDataWithBaseURL("file:///android_asset/", myHTML, "text/html", "UTF-8", "");
cheers