4

I'm trying to display an image in a WebView in an Android app. The image exists in the assets folder of my Android project. The HTML is programmatically built and has this image ref in it:

The HTML is loaded into the WebView using:

webView.loadDataWithBaseURL( urlStr, htmlText, "text/html", "utf-8", urlStr );

urlStr = a base url needed to find other resources. htmlText = the programmatically generate HTML

The WebView loads the HTML fine, but the image is displayed as "missing". I have verified that the image exists at that location in the assets. Nevertheless it does not appear in the WebView.

I have seen numerous postings and tutorials saying that this should work, but it doesn't for me. This is on a 3.2 Android tablet. Anyone know if this only works on some versions of Android? Any thoughts about why it doesn't work in my case? Thanks.

btschumy
  • 1,435
  • 1
  • 18
  • 35

2 Answers2

4

enter image description here

 webView.loadDataWithBaseURL("file:///android_asset/", sourse, "text/html", "UTF-8", null);
Georgy Gobozov
  • 13,633
  • 8
  • 72
  • 78
  • thank you so much; it's working in my case. my other question is every time we have to store image to asset folder what if i have number of images or i got all from network call!! i didn't try that yet but still asking. can you help me to solve how to save all pages and hidden content in pdf? here's my question https://stackoverflow.com/questions/54870164/convert-html-into-pdf-using-webview-not-display-full-content-with-images – Rucha Bhatt Joshi Feb 27 '19 at 10:12
4

OK, I finally figured this out. Apparently there is a bug somewhere in the Android code where it fails if the image path has a space in it. So:

<img src="file:///android_asset/SkyInfo/images/Deep Sky/M13-Misti.jpg">

will fail to load the image. If you change it to:

<img src="file:///android_asset/SkyInfo/images/DeepSky/M13-Misti.jpg">

it will work (assuming you've renamed the directory).

Note:

  • this is only a problem when reading from the assets.
  • appears to be an issue with Android 4.x. I have encountered this issue on 4.0.4 and 4.3 versions but spaces work just fine in 2.3.x version.

Come on Google, spaces in directory names have been common for 15 years. Get with the program.

Vladan
  • 371
  • 6
  • 13
btschumy
  • 1,435
  • 1
  • 18
  • 35