webview.loadData() won't load local images - android

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

Related

Loading of base64 images in WebView

I've got a question related to the showing HTML data inside WebView.
I have quite big HTML string with some images with src in base64 format. I'm reading this data from file. File reading is quite fast and I have no issues with this.
When it's only one image inside HTML - it works fine. But when at least a couple - it's lagging a lot. (It's loading about 30-35 seconds)
I tried to speed up it but no result.
This is the way I load HTML string.
WebView.loadDataWithBaseURL("file:///", StringEscapeUtils.unescapeHtml4(hmtl), "text/html", "UTF-8", null);
I use this function with base URL "file:///" because I'm going through the links(local) inside this file. So I guess it's obligatory to use this kind of function.
Can anyone help me with a solution?

WebView loadDataWithBaseURL method cannot load images

I have a html string containing seveal img tags which I am passing to webview's loadDataWithBaseURL method like
String data = "some html with <img> and <link>.....";
wview.loadDataWithBaseURL("http://dummy.baseurl/", data, "text/html", "UTF-8", null);
if I dont pass the first parameter html can be displayed but subsequent requests for or css files are not triggered thats why I am passing a dummy baseUrl.
Running the code when I try to look what requests were made under shouldInterceptRequest() like below
wview.setWebViewClient(new WebViewClient() {
#Override
public WebResourceResponse shouldInterceptRequest(WebView view,
String url) {
Log.d("url="+url, "resources");
....
}
});
the I can see outputs like
http://dummy.host.name/images/face.jpg
etc
but my original html contains ".." in img src like <img src="../images/face.jpg"> trouble is parent directory (..) part is ignored by webview
this ".." is important for me I cannot figure out why it is skipping that part
EDIT
I am loading images from a zip file so inside shouldInterceptRequest() I can put necessary logic but first I should have correct src.
I also noticed that if path is appended to baseUrl, they are also ignored for example
http://dummy.baseUrl/one/two/
becomes (looking from request logs)
http://dummy.baseurl/
I suspect if these two are related !
Where do you want to load the images from? If you're trying to load them from the phone you need to use the assets folder.
https://stackoverflow.com/a/7268695/642161
I resolved my problem using a hack, not sure a better solution exist!
It looks like baseUrl and src are merged to create final request urls so if any ".." present in src it will be used to recalculate final url and they disappear no matter if top level directory exist.
I changed baseUrl to
file:///android_asset/x123_/x123_/x123_/x123_/
Here "x123_" is any random character sequence one can take but should be least likely to appear in "src"
Now count the mumber of "x123_" in request url inside shouldInterceptRequest() if it is 4 (as in this example) there were no ".." in src otherwise number of ".." = 4 - count

Images not displaying in Android WebView

I have a situation where I am trying to display user-generated HTML in a webview using loadData. My code is something like this:
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
"<html><head>" +
"<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />" +
"</head><body>";
content += htmlStr + "</body></html>";
wv.loadData(content, "text/html", "UTF-8");
It works pretty well in most cases, but I am having trouble getting certain types of images to display. In most of my testing, inserting <img src="..."/> tags worked fine, but I found that links to images on Photobucket would not display at all; I get a little box with question mark in it instead of the image.
Clicking on a link to an image on Photobucket tends to take you to the page on which that image is viewable on their website, rather than just the raw image itself. I have a feeling that the issue is related to this. I suspect that it may be a "Referer" issue, or perhaps user-agent, or something of that nature, but I cannot for the life of me get this to display properly.
I have tried switching to loadDataWithBaseURL and providing a BaseURL (as I believe this will be used as the referer url) but that made no difference. I have also tried using loadUrl("http://photobucket..." instead and providing a HashMap with the Referer header manually set, but that did not work either. Actually, switching to loadUrl made it immediately redirect to the device's browser to load the Photobucket page. I attempted to provide a custom WebViewClient and override shouldOverrideUrlLoading, but the best I got it to do was to display the full Photobucket page inside the WebView.
I am sure this is not a specific issue with Photobucket, that just happens to be the site that I discovered this problem with while I was testing.
I would really like to figure some way to deal with this situation so that this can work correctly, but I have been as yet unable to find any helpful direction on SO or the internet at large. Does anyone have any ideas?
I would wait until Photobucket finishes their recent updates before further testing...while you stated you are sure it is not a specific issue with Photobucket the internet is now awash with posters not able to view Photobucket linked to images with android based devices. If your code works with all other images not hosted on photobucket your code is good.

Why is WebView unable to open some local URLs (Android)?

I have a WebView that I'm using to open some files stored in the assets/ directory of my project. It works fine for most of the files, but there's one in particular (and I'm sure others I haven't found) that it just will not open.
The file I'm having problems with is named:
"assets/ContentRoot/Photos/XXX Software Logo - jpg - 75%.JPG"
When I pass it to WebView, and it shows the error page, it shows it as:
"file:///android_asset/ContentRoot/Photos/XXX%20Software%20Logo%20-%20jpg%20-%2075%.JPG"
I then tried running URLEncoder.encode() on it and got the error page with the URL presented as:
"file:///android_asset/ContentRoot/Photos/XXX+Software+Logo+-+jpg+-+75%.JPG"
Neither of these URLs were able to open the file (and they both look okay to me). Anyone have any ideas?
UPDATE: If I encode the % by hand (using %25, as commonsware.com suggested) then it loads the image, but it tries to parse it as text, not as an image, so I just get a lot of (basically) garbage.
Also, referring to the image in an HTML document with a relative URL isn't working (probably because it's not being parsed as an image?):
<img src="../Photos/XXX%20Software%20Logo%20-%20jpg%20-%2075%.JPG" />
<img src="../Photos/XXX%20Software%20Logo%20-%20jpg%20-%2075%25.JPG" />
Okay, after spending way too long on this, I've figured out what's going on. Basically, if images stored in the assets/ directory contain a space (e.g., " ") in their file name, they won't render as images.
myWebView.loadUrl("file:///android_asset/testimage.jpg");
works fine. However,
myWebView.loadUrl("file:///android_asset/test+image.jpg");
just throws a not found error and
myWebView.loadUrl("file:///android_asset/test image.jpg");
// and
myWebView.loadUrl("file:///android_asset/test%20image.jpg");
show it improperly displayed (as text... see screenshot in question).
This unexpected behaviour is present on (at least) 1.5, 1.6, and 2.0 and I filed a bug report.
Try getting rid of the % in the filename. Or, escape it as %25.
I would guess that WebView only understands text related content types so it faithfully treating your JPG as base64 encoding, decodes and displays resulted gobble-goop as text. I don't really know if it's possible to set content type for WebView but as workaround you can try to throw img tag inside html tag and load resultet page. Also you probably can only use WebView#loadDataWithBaseUrl

Download and display html files

I have to download contents of an HTML file (which uses image) via REST API. Then store them for offline use. When needed I want to display the HTML page with a WebView (of course with image). The REST result should look something like:
{
"id": 45,
"html": "<!DOCTYPE html><html><body><h1>My Heading</h1><p>My paragraph.</p><img src='abc.com/images/54289847.jpg' alt='any' width='104' height='142'></body></html>",
"imagePath": "abc.com/images/54289847.jpg",
"moreData": "something more"
}
So, what will be the most efficient way to do this?
I'm planning encrypted contents of HTML will go to local storage in any file. Same thing for the images. And then decrypt, and load to WebView. But will it work for images?
I don't need any code, just suggest me a way.
in this example string is loaded to webview
String summary = "You scored 192 points.";
webview.loadData(summary, "text/html", null);
what if you get string from input stream and pass it to web view IOUtils.toString(context.getResources().openRawResource())
Im not an android developer, but can't you get the "image data-url" and use as the image itself?
For example your avatar's data-url is:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADYUlEQVRYhe2W7UtTYRjGj2VqZSFC4AtSS+d8Wa5pKaWbnql7dVMsxEjDisjMVAoKkvxgUEFZhJVT6MWioBeCvkX0j/SxP0D6srOzuZ1zdZ9ztnl0x9cZEvjh5kx39jy/+7qv+34ehhnwYUtjG+D/AbiqipX+t+kA0uLDPhT2enCxw4VJuwNTLXb4Ke46HXCddiPzQtvCu5sKMOJDTbcH362tEA02oJgFypdECYs/lc2453Ag+3Lb+iGW/WLIi3HKEBUW2sQC7jCLQIV2CDGYOWMznKSIBJ4awDUvPrJ2oJBFuLMckTs54L1GBHQOBKoalwWRFdHb0N/uTAGA6MdclLmOBVdmQfRJBvCVgTiVicjoAYROlSNQbltZDYKwdLnXVo6lhjOf8QClNnDSgpVN4FkThIls4A0DfGIQ7tMhkOdBoMy2OFRQkhK/Tc1IG/CuE4Dc/oMMJy0gLyY9i5wItZohTmQCMwyio7ngm46BbzCDt1I0VNOzGsH6Ohk4AUGGvd7mXF0Fdfa6HsreEMuegjNbMD9cBFHK3p8GTDMyBGbTFEVmGeX5gcAIkKs9qUDHVPhV1wJmcBUV1ACDPie5fiF7ru4EhGc7gXeMsrlWzMRK01NCJl3wgpSEVEo9JbWiCuo/pmm4JOSPL6RvQWQoX9lIA0Cc3I35/iJwpc2J7NVl6O10rRHgig8/La1JAIGDDgXgrcbmM+ngJdmLXOCO1Ce3JcWljlQBaADN3yhILgMpIvozECSFeHcVIg+zwBmsKQAsUwKpvXjrUYgv0xcD+CneM7I6kZE8iGRITuoCdTuuqwRLTagC4IxNEJ9nLfjgxQ4I4/sRpQkZvZ0L8RUjl4i3mZSZsCETarRhwohkMOHRPgVgilrwdRqEx9kIn9XTHKhFdCwH+EydcJ6G1CHbBttQaxAljMgicitf3kR4sAfC010IdRkQtB6nDR0ItRuAL1SOwQL53Y0NIq1RrJoJvMuE8Lli2XBBtkbZSALV2RDyGYFvBHAzn4BSGcXqw6iYTSqF1BGyydSHEX2WgKL39yLcXQpB35jCYRSP+HGsBaEVZFLebqb3rfJvUjuO4xG/kFA2kqQrgchHsMmCORO7SRcSVTlqut1rv5L1beaVTGXMrbuULgXZkmv5v45tgK0G+At38NtPjlXm2AAAAABJRU5ErkJggg==
If you paste this in your computer's browser(as url) and/or in <img> tag, you'll see your avatar.

Categories

Resources