Context :
My app sometimes displays "Sheets" which are html files that contain texts and images :
<p>image description </p>
<p><img src="/api/medias/get/videos/56afad6447eba61c8099544b?thumbnail=true&company=4f86d0a9d655ab9794f5d1d2&fullSizedCover=true"
alt=""
data-id="56afad6447eba61c8099544b"
data-type="video" data-width="640" data-height="1136" /></p>
Then I use body.loadDataWithBaseURL(<my api url>, body, "text/html; charset=UTF-8", null, null);
I don't think it's relevant but I'll say it just in case, I have a template body that contains css and javascript. the js script detect images click and transmit the "data-id" to an android method (via a JavascriptInterface). In this case it opens a video player and plays it.
Problem :
My app allow the user to download these Sheets for latter offline vizualisation. So I download the html, then download the images to my local private directory (Context.getFileDir()) and change the src of the html to set the "thumbnail" sources to the images I downloaded :
<p>video</p>
<p><img src="69c623955ecb5bd414f908cd383f3809.jpg"
alt=""
data-id="56afad6447eba61c8099544b"
data-type="video" data-width="640" data-height="360" /></p>
My question is : What do I put as base url to my webview for me to get the expected behaviour (ie : display the downloaded images).
I tried Context.getFileDir().getAbsolutePath(), content://com.android.htmlfileprovider and some other.
Should I do differently ?
Thank a lot,
This works well:
Picasso.with(iv.getContext()).load(new File(getContext().getFilesDir() + "/" + "69c623955ecb5bd414f908cd383f3809.jpg")).into(iv);
The html :
<p>video</p>
<p><img src="69c623955ecb5bd414f908cd383f3809.jpg" alt="" data-id="56afad6447eba61c8099544b" data-type="video" data-width="640" data-height="360" /></p>
my base url : baseUrl = Uri.fromFile(getContext().getFilesDir()).toString();
And finaly :
webview.loadDataWithBaseURL(baseUrl, body, "text/html; charset=UTF-8", null, null);
You can try to use null baseUrl if you already downloaded/have template, and just pass that html template as a body to webview.
And before passing find img tags in it and set img src with a full path to locally stored file. Smth like:
Document doc = Jsoup.parse(newHtml);
Elements elems = doc.getElementsByTag("img");
for (Element el : elems) {
String filename = el.attr("src"); //presumably only name
String picUri = "file:///" + folder + "/"+filename;
el.attr("src", picUri);
}
web.loadDataWithBaseURL(null, htmlBody, "text/html", "UTF-8", null);
Related
In my local storage I have the following folder
/data/data/com.test.testapp/files/1/images
and the following file exists.
/data/data/com.test.testapp/files/1/images/f.png
These were stored/retrieved using context.getApplicationContext().getFilesDir()
In my HTML I have "<img src="f.png" />"
I can get TextView working with html/images using an ImageGetter, which effectively returns a drawable from:
Drawable.createFromPath(targetFile.getAbsolutePath());
Where the targetFile is as described above ends up being (/data/data/com.test.testapp/files/1/images/f.png)
However, when I try to use WebViewer as follows (I've pasted in the string for ease):
String url = "file:///data/data/com.test.testapp/files/1";
webViewer.loadDataWithBaseURL(url, content, "text/html", "utf-8", null);
Where content ends up with the same text as my TextView.
All I get is an image placeholder, i.e. it didn't find it.
OMG! ;)
How petty are those people at Google!
All I had to do was append a slash to the url so the base url:
file:///data/data/com.test.testapp/files/1
When changed to
file:///data/data/com.test.testapp/files/1/
Works.
WebView web_view = (WebView) findViewById(R.id.webView1);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setPluginsEnabled(true);
web_view.getSettings().setAllowFileAccess(true);
String data;
data = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<html>"
+ "<head>"
+ "<title>My First chart using FusionCharts XT</title>"
+ "<script type=\"text/javascript\" src=\"FusionCharts.js\">"
+ "</script>"
+ "</head>"
+ "<body>"
+ "<div id=\"chartContainer\">FusionCharts XT will load here!</div>"
+ "<script type=\"text/javascript\">"
+ "FusionCharts.setCurrentRenderer(\"javascript\");"
+ "var myChart = new FusionCharts(\"FusionCharts/Line.swf\", \"myChartId\", \"400\", \"300\", \"0\", \"1\" );"
+ "var dataString =\"<chart> <set label='0.00' value='0'/><set label='5.00' value='2' /><set label='7.00' value='3' /><set label='9.00' value='4' /><set label='12.00' value='2' /></chart>\"; "
+ "myChart.setXMLData(dataString);"
+ "myChart.render(\"chartContainer\");" + "</script>"
+ "</body>" + "</html>";
Log.i("info", "Html " + data);
web_view.loadData(data, "text/html; charset=UTF-8",null);
In my project i am using fusion charts. I am making a html string data and load it in WebView as in above code sample. When i run this html file in browser it runs and make me Fusion charts, But when i am doing this with for android Web view it is not loading in my Web View.
I have already Enable javascript.
I paste javascript file in to assets folder.
First of all, the browser you mentioned is a browser on your device or is it a browser in a computer?
Now, if it worked in the android browser (or a browser in your device), then the problem is because the javascript files are on your assets folder. When you indicate a resource through relative path (the way you are using), the webview searchs it relative to the same folder as your html file is. Since you are using a String as your "html file", I would recommend using the loadDataWithBaseURL(). I made an usage example below using the assets folder as the base URL, try it.
web_view.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8",null);
public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)
Added in API level 1
Loads the given data into this WebView, using baseUrl as the base URL for the content. The base URL is used both to resolve relative URLs and when applying JavaScript's same origin policy. The historyUrl is used for the history entry.
Note that content specified in this way can access local device files (via 'file' scheme URLs) only if baseUrl specifies a scheme other than 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.
If the base URL uses the data scheme, this method is equivalent to calling loadData() and the historyUrl is ignored.
Parameters
baseUrl the URL to use as the page's base URL. If null defaults to 'about:blank'.
data a String of data in the given encoding
mimeType the MIMEType of the data, e.g. 'text/html'. If null, defaults to 'text/html'.
encoding the encoding of the data
historyUrl the URL to use as the history entry. If null defaults to 'about:blank'.
You can try passing the assets folder as the baseUrl, so my guess would be that your code would be like this
Hope this helps!
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?
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", "");
You don't need to put full path of your image into html.
img src="images/test1.jpg"
Instead
img src=\""+ imagePath + "\"
I'm loading some data, containing latin-1 characters, in a WebView using
String uri = Uri.encode(html);
webview.loadData(uri, "text/html", "ISO-8859-1");
When displayed, the latin1 characters are replaced by weird characters.
If I load the html directly in a TextView (just to test), latin characters are properly displayed.
Anybody can help?
Thanks
html:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- some html -->
</html>
myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);
This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.
Tested on 2.3 and 4.0.3.
In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.
You should always use UTF-8 encoding. Every other character encoding has become obsolete for many years already.
Only way to have it working, as commented here:
webview.loadDataWithBaseURL("fake://not/needed", html, "text/html", "utf-8", "");
No URI encoding, utf-8... loadData bug?
String start = "<html><head><meta http-equiv='Content-Type' content='text/html' charset='UTF-8' /></head><body>";
String end = "</body></html>";
webcontent.loadData(start+ YOURCONTENT + end, "text/html; charset=UTF-8", null);
One of solution of problem.
I have display © 2011 and it was displaying ©.
With the below code i have achieved displaying correct value © 2011
webViewContent.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
AFAIK that:
Firstly, loadData() method is used to load raw html code.
Secondly, just put the html code directly to the loadData(), don't encode it
You might wanna try like this:
webview.loadData(uri, "text/html", "ISO-8859-1");
Cheers!
I too had the problem of getting a weird character like  here and there. Tried different options, but the one that worked is below.
String style_sheet_url = "http://something.com/assets/css/layout.css";
String head = "<head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"" + style_sheet_url + "\" /></head>";
String locdata = "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + head + "<body>"+ data + "</body></html>";
wv_news_text.loadData(locdata, "text/html", "utf-8");
wv_news_text is the WebView.
Info from Java docs about loadData method
Loads the given data into this WebView using a 'data' scheme URL.
Note that JavaScript's same origin policy means that script running in
a page loaded using this method will be unable to access content
loaded using any scheme other than 'data', including 'http(s)'. To
avoid this restriction, use loadDataWithBaseURL() with an appropriate
base URL.
The encoding parameter specifies whether the data is base64 or URL
encoded. If the data is base64 encoded, the value of the encoding
parameter must be 'base64'. For all other values of the parameter,
including null, it is assumed that the data uses ASCII encoding for
octets inside the range of safe URL characters and use the standard
%xx hex encoding of URLs for octets outside that range. For example,
'#', '%', '\', '?' should be replaced by %23, %25, %27, %3f
respectively.
The 'data' scheme URL formed by this method uses the default US-ASCII
charset. If you need need to set a different charset, you should form
a 'data' scheme URL which explicitly specifies a charset parameter in
the mediatype portion of the URL and call loadUrl(String) instead.
Note that the charset obtained from the mediatype portion of a data
URL always overrides that specified in the HTML or XML document
itself.
Following code worked for me.
String base64EncodedString = null;
try {
base64EncodedString = android.util.Base64.encodeToString((preString+mailContent.getBody()+postString).getBytes("UTF-8"), android.util.Base64.DEFAULT);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(base64EncodedString != null)
{
wvMailContent.loadData(base64EncodedString, "text/html; charset=utf-8", "base64");
}
else
{
wvMailContent.loadData(preString+mailContent.getBody()+postString, "text/html; charset=utf-8", "utf-8");
In my app I'm making a basic HTML help document.
I wanted my app's logo in the HTML img tag itself, but I don't know how I'd reference to the logo which will be stored in assets.
Is this possible, if so how?
Thanks for the help!
Put your Logo into the assets directory eg: assets/logo.png
Then load your html with:
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "utf-8", null);
Reference your img like:
<img src="logo.png">
Store the images in assets folder:
Read the image in the html from assets with file:///android_asset/
for example:
String sHtmlTemplate = "<html><head></head><body><img src=\"file:///android_asset/img/mybadge.png\"></body></html>";
load inside the WebView:
webView.loadDataWithBaseURL(null, sHtmlTemplate, "text/html", "utf-8",null);
You can reference assets with this URL syntax:
file:///android_asset/YourAssetFilename
dump them into assets folder and just put in the html
<img src="filename.png">
simple as that
Put your Logo into the assets directory
Example : assets/logo.png
Then
String imgData="<img src=home.png>";
webView.loadDataWithBaseURL("file:///android_asset/", imgData, "text/html", "utf-8", null);
Consider we have placed an image your_image.png in assets/imgs.
In earlier versions of android you can directly access images like below.
webView.loadData("<img src='file:///android_asset/imgs/your_image.png'/>",
"text/html", "UTF-8");
But can't access files directly in latest versions due to added security concerns. for the latest versions we need to use WebViewAssetLoader. refer the below code.
Helper class to load local files including application's static assets and resources using http(s):// URLs inside a WebView class. Loading local files using web-like URLs instead of "file://" is desirable as it is compatible with the Same-Origin policy.
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
.addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this))
.build();
webView.setWebViewClient(new WebViewClient() {
#Override
public WebResourceResponse shouldInterceptRequest(WebView view,
WebResourceRequest request) {
return assetLoader.shouldInterceptRequest(request.getUrl());
}
});
webView.loadData("<img src='https://appassets.androidplatform.net/assets/imgs/your_image.png'/>",
"text/html", "UTF-8");
for more information please refer android dev portal links
https://developer.android.com/reference/androidx/webkit/WebViewAssetLoader
https://developer.android.com/jetpack/androidx/releases/webkit?fireglass_rsn=true