Android: Unable to load simple html data having javascript file in WebView? - android

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!

Related

Load Image from local private directory in a webview

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);

How to get editable web view content to string in Android.?

I want to implement a Rich text editor by using a webview in android. Content can be loaded by using a HTML file (which resides in assets) without any problem. But if user has edited the content of the webview (with all the formatting), I need to get the modified content as a HTML string and save it in the database. How can I do this?
I tried in many ways but it seems that we need to pass a URL to get the content of the webview. But after editing the webview content, how can we get the edited URL? or current updated webview content to HTML formatted string?
Using below code I made editable web view.
String msgBody = "<html>\n"+
"<body>\n"+
"<div id=\"content\" contenteditable=\"true\" style=\"font-family:Helvetica;font-size:14px\">" + a +" </div>\n"+
"</body>"+
"</html>";
// wbview = (WebView)this.findViewById(R.id.wbview);
wbView.getSettings().setJavaScriptEnabled(true);
wbView.loadDataWithBaseURL("", msgBody, "text/html", "UTF-8", "");
wbView.setHorizontalScrollBarEnabled(true);
wbView.setVerticalScrollBarEnabled(true);
In iOS we can get it easily by using below code line.
NSString* html=[_tbEmail.webView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('body')[0].innerHTML"];

Encoding issue with WebView's loadData

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");

Does webview take HTML tag <object>?

I tried many times and try to use HTML tag <object>, but app just crash and disappear.
Each time when I use normal html tag such as <html>, <body>, <h1>, <div>, <td>, <tr> etc. Those can be shown directly without any error.
This time I try to embed an <object> tag to webview and it always crash!
Does anyone who know how to do this directly inside code? OR, webview just cannot do this?
here is my code.
String html =
"<html>" +
"<body><h1>This is a test !!</h1>" +
"<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width='200' height='200'></object>" +
"<param name='quality' value='high'>" +
"<param name='allownetworking' value='internal'>" +
"<param name='allowScriptAccess' value='never'>" +
"<param name='movie' value='http://video.yutube.com/flv2.swf?i=20100129LqvamMPB&d=360.25&movie_stop=off&no_progressive=1&otag=1&sj=5&rel=1'>" +
"<param name='allowFullScreen' value='true'>" +
"<embed src='http://video.yutube.com/flv2.swf?i=20100129LqvamMPB&d=360.25&movie_stop=off&no_progressive=1&otag=1&sj=5&rel=1' width='200' height='200' quality='high' allownetworking='internal' allowscriptaccess='never' allowfullscreen='true' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed>" +
"</object>" +
"</body></html>";
mWebView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
You have one <object> tag and two </object> tags. The first </object> has got to go.
The embed tag is for browsers that don't recognize the object tag. Those browsers will see the embed tag and will try to use it. Browsers that support the object tag will use the object and ignore the embed, as long as the embed is within the object. If the embed is outside the object, object aware browsers may load both the object and embed tags.
WebView can definitely handle the html tag. I don't think you should use loadDataWithBaseURL though, try this instead:
mWebView.loadData(html, "text/html", "UTF-8");
I'm not too sure your <object> will work though...
Here's a better way to play a YouTube video if that's all you need:
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v=<video-id>")));
Put your video id in place of the <video-id>

Android webview giving blank screen when loading data from HTTPS

I have a problem with an URL that starts with https. It's showing a blank white screen whereas links, starting with http, loads successfully in Android webview.
With logs I'm sure that data is coming from HTTPS also but is not displaying in the view. Please help me. Some sample code or link will be most appreciated.
HI,
I read your question, I don't know what is your exact issue if you have data then you can use these line of code to display it in webview
encoding contains html tags like <p> aadfasdf asdf ds </p>
public static final String HTML_FORMAT =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">" +
"<html><head><title></title>"+
"<style type=\"text/css\">" +
"'body {color:#FFFFFF;background-color:#000000;font-size: 10pt}'" +
"</style>" +
"</head>" +
"<body>" +
"%s" +
"</body></html>";
String textHtml = String.format(Constants.HTML_FORMAT,encoding);
wv.setBackgroundColor(Color.BLACK);
wv.loadDataWithBaseURL(null, textHtml, "text/html","utf-8", null);
try this hopefully you will get your required result.

Categories

Resources