Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android webview loadDataWithBaseURL how load images from assets?

In my project I have a files:

"MyProject/assets/folder1/image1.jpg"
"MyProject/assets/folder1/index.html".

In webView I need to open index.html (with images).

I trying this code:

String baseUrl = "file:///android_asset/folder1/";
webView.loadDataWithBaseURL(baseUrl, readFileAsString("index.html") , mimeType, "UTF-8", null);

But images don't loading.

If I put images to "assets" directory (MyProject/assets/) and make baseUrl = "file:///android_asset" images are loaded correctly;

How load images not only from root assets directory, but and from assets/folder1?

like image 795
user1367713 Avatar asked Jan 17 '13 08:01

user1367713


2 Answers

try like this

WebView webview = (WebView)this.findViewById(R.id.webview);


String html = "<html><head><title>TITLE!!!</title></head>";
html += "<body><h1>Image?</h1><img src=\"icon.png\" /></body></html>";


webview.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "UTF-8", null); 

For more information try this link

perfect LoadDataWithBaseurl

like image 58
Janmejoy Avatar answered Nov 16 '22 02:11

Janmejoy


I think you have to set the base to assets and add the sub folders to your image src's like this:

webView.loadDataWithBaseURL("file:///android_asset/", readAssetFileAsString("folder1/index.html"), "text/html", "UTF-8", null);

Html: <img src="folder1/image1.jpg">

This worked for me on Android 5.1

private String readAssetFileAsString(String sourceHtmlLocation)
{
    InputStream is;
    try
    {
        is = getContext().getAssets().open(sourceHtmlLocation);
        int size = is.available();

        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        return new String(buffer, "UTF-8");
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

    return "";
}
like image 25
behelit Avatar answered Nov 16 '22 04:11

behelit