简体   繁体   中英

webview.loadData() won't load local images

I have an html page that's built dynamically. Some of the images come from an internet url and others i want to load from the Assets folder. The pages correctly renders the internet images, however, it just refuses to load local images. I'm tried many variations including the following and none will load the local images. If everything is loaded from the internet url, the entire pages renders correctly but I really don't want to go to the internet for static content that won't change. Any ideas?

String pageData="a bunch of html markup...";

//-- i had to remove the < from the img tag below to get by the spam filter on this forum-->

//--try 1--> pageData += "img src='file:///data/data/(my package)/files/image1.png' alt='my image'>";

//--try 2--> pageData += "img src='/data/data/(my package)/image1.png' alt='my image'>";

//--try 3--> pageData += "img src=' src='data:image/jpeg;base64,'" + readAssetFileAsBase64("image1.png") + "' alt='my image'>";

//--try 4--> explosives!

The page is rendered using..

webview.loadData(pageData,"text/html",null);

but I've also tried

webview.loadDataWithBaseURL("file://", s, "text/html","windows-1252" ,null);

I can't use .loadUrl() since the page is built dynamically. I suppose I could write the dynamic page out to disk the call .loadUrl() but that doesn't seem so efficient.

You need to make sure you load the html with a base url, although that base url doesn't need to be anything pertinent

webView.loadDataWithBaseURL("fake://not/needed", htmlString, mimeType, encoding, "");

and then you can reference things in the assets folder using something like this

file:///android_asset/image1.jpg

the "android_asset" path seems to be the thing you haven't tried yet. If your files are not in your asset folder then you need to serve them with a ContentProvider, see this tutorial from my site: http://responsiveandroid.com/2012/02/20/serving-android-webview-resources-with-content-providers.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM