3

I would like to set some html content in my webview with some pictures. I've read on the internet i must use loadDataWithBaseUrl to do such a thing because i need to link the folder of images (basUrl) in order.

My html content nicely loads, i can even ran the javascripts perfectly, but for some reason my images cannot be loaded.

Somewhere i've read there are some security reasons and thats why i cant load images from sd card to webview and some says it can be easily done via loadDataWithBaseUrl, so i really dont know which one is true.

Here is my method i tried, maybe with some mistakes so dont be rude:

I got my html file here:

mnt/sdcard/com.mypackage.myproject/3/3.html

My images are here:

mnt/sdcard/com.mypackage.myproject/3/images/Cover.png

And this is my content loading:

myWebView.loadDataWithBaseURL("file:///mnt/sdcard/com.mypackage.myproject/3", myHtml, "text/html", "utf-8", "");

In my html code:

<img src="images/Cover.png" alt="Cover.png" height="820"/>

So as you see i give the baseUrl, and for some reason the webview cannot load my images.

As many said, this can be a solution:

mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file:/"+ base + "/test.jpg";
String html = "<html><head></head><body><img src=\""+ imagePath + "\"></body></html>";
mWebView.loadData(html, "text/html","utf-8");

BUT, i have 700 different html files and there are many images in many different places... so i cannot modify the html code.

Is there a way to link the image folder to my html files to properly use them as a baseUrl?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222

2 Answers2

3

You have a syntax error in your loading statement. You have to put : after file

myWebView.loadDataWithBaseURL("file:///mnt/sdcard/com.mypackage.myproject/3", myHtml, "text/html", "utf-8", "");
Iñigo
  • 12,723
  • 2
  • 31
  • 31
0

You don't need to put full path of your image into html.

img src="images/test1.jpg"

Instead

img src=\""+ imagePath + "\"