Android WebView incorrectly handling newlines in preformatted text - android

If I push this HTML into WebView:
webView.loadData("<html><body><pre>line 1\nline 2</pre></body></html>", "text/html", "utf-8");
it renders as (in emulator and also on device)
line 1line 2
as opposed to
line 1
line 2
as I would expect. If I save this HTML to the sdcard and open the file in the browser, it renders fine. I suppose I am doing something wrong, or this may be a bug. Any way, I want to programatically push HTML with preformatted newlines into a WebView and have the newlines rendered.

The string passed to loadData needs to be URI-escaped.
You can use URLEncoder.encode() to do that, but for some reason WebView does not decode the '+' back to a ' '. One work around is to replace all the '+' with '%20' yourself.
For example (and with the '+' translation):
try {
webview.loadData(URLEncoder.encode("<html><body><pre>line 1\nline 2</pre></body></html>", "utf-8").replaceAll("\\+", "%20"), "text/html", "utf-8");
} catch (UnsupportedEncodingException uee) {
Log.e("webview", "", uee);
}

Try this:
webView.loadDataWithBaseURL(...)
More info here

Also you can use
chapterWebView.loadDataWithBaseURL("file:///android_asset/NTImages/", message.replaceAll("\\n", "<br/>") , "text/html", "utf-8", "utf-8");

Related

Hindi Character will not display in web view correctly

I had Database in which data stored in hindi as \u092e\u0948\u0902 \u0924\ and setting that content to webview using below.
webview1.loadData(hindi_content, "text/html", "UTF-8");
But it will display as
I don't know why that's happening. Any one please suggest. how to fix that !
This happens because of a bug with the encoding parameter of loadData in most Android versions. This parameter is ignored for some reason so the UTF-8 based hindi characters will not be rendered.
To fix this you can use one of the following alternatives.
webview1.loadData(hindi_content, "text/html; charset=UTF-8", null);
webview1.loadDataWithBaseURL(null, hindi_content, "text/html", "utf-8", null);
This is a duplicate of this answer:
You will also need to unescape those sequences and to do that refer to How to Unescape Unicode in Java
Rendering UTF-8 in a WebView using loadData has been broken in some form or fashion forever.
Issue 1733
Use loadDataWithBaseURL instead of loadData.
// Pretend this is an html document with those three characters
String scandinavianCharacters = "øæå";
// Won't render correctly
webView.loadData(scandinavianCharacters, "text/html", "UTF-8");
// Will render correctly
webView.loadDataWithBaseURL(null, scandinavianCharacters, "text/html", "UTF-8", null);
Now the part that is truly annoying is that on the Samsung Galaxy S II (4.0.3) loadData() works just fine, but testing on the Galaxy Nexus (4.0.2) the multi-byte characters are garbled unless you use loadDataWithBaseURL(). WebView Documentation
you will need to use font in order to support hindi (Hindi language is not yet fully supported by android)
create Singleton instance of Typeface and invoke createFromAsset();
and add it to WebSettings like this
WebSettings webSettings = webView.getSettings();
webSettings.setFixedFontFamily(InstaceOFTypeFace);
Finally I have come up with the solution of Loading hindi content to the webview.
I had simply change my loading string and unfortunately it will work.
webview.loadData(Hindi_css, "text/html; charset=UTF-8", null);
Thank you all for your effort. :)
You can use this one also.
String uri= Uri.encode(html file/url);
webView.loadUrl(uri);
may be this will help you.

'Webpage not available' with WebView.loadData() ONLY in emulator

I'm calling loadData on my WebView and passing it some HTML in the form of a String like so:
webView.loadData( htmlString, "text/html", "utf-8" );
It works fine on my Galaxy Tab 10.1, but the WebView displays:
Webpage not available
when running on the emulator with everything set up to match my Galaxy Tab. Setting android.permission.INTERNET in the manifest has no effect, though I shouldn't need that permission since I'm rendering in-memory HTML, and not accessing anything over the data connection.
What's going on?
Try with this code
webView.loadData( URLEncoder.encode(htmlString).replaceAll("\\+"," "), "text/html", "utf-8" );
insted of
webView.loadData( htmlString, "text/html", "utf-8" );
it should work, because sometimes character like '%', '\', '#' creates problem if its not properly Encoded
In 2.x platforms loadData() fails in some cases (it requires the html to be escaped), use loadDataWithBaseURL() instead and pass null for baseUrl and historyUrl:
webView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
Actually thanks for #Viraj for the answer.
Google currently deprecated the above and you should use this instead:
webView.loadData(URLEncoder.encode(mAdvertisement.getContent(), "UTF-8").replaceAll("\\+", " "), "text/html", "UTF-8");

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

Android: WebView loadDataWithBaseURL does not display captcha image

I am trying to display a captcha jpeg image (which is generated dynamically by a Java servlet) in my application's WebView, however, it will sometimes display a blue question mark instead of the captcha image. Below is what I have in my shouldOverrideUrlLoading(WebView view, String url) method of MyWebViewClient class that extends WebViewClient
I have internet access enabled in my manifest and the problem occurs for about 80% of the time. i.e. Sometimes the image does show up correctly but very rare though.
There was another similar question here Image with dynamic src loads in Android browser, but not in Webview, but does not seem to have a definitive answer.
Thanks in advance
try
{
CookieSyncManager.getInstance().sync();
Log.v("Hello","CookieStore: " + httpClient.getCookieStore().toString());
HttpResponse response = httpClient.execute(httppost);
data = new BasicResponseHandler().handleResponse(response);
view.loadDataWithBaseURL(URL.toString(), data, "text/html", "UTF-8" , null);
//Log.v("Hello","Data: " + data.toString());
}
catch (ClientProtocolException e)
{
Log.v("Hello","ClientProtocolException:Overriding");
Log.v("Hello",e.toString());
e.printStackTrace();
}
catch (IOException e)
{
Log.v("Hello","IOException:Overriding");
Log.v("Hello",e.toString());
e.printStackTrace();
}
I just got the same problem. I identified the issue and solved it (in my case). You can notice that in HTML code, the img tag has the src pointing to the relative path of the site. Something like <img src="/relativepath/captcha.jpg?12345678"/>. All you have to do is to inject the full path (host + relative path) to obtain something like <img src="http://yourhost.com/relativepath/captcha.jpg?12345678">.
Read the HTML code, line by line
Match the sequence "<img src" (maybe something a little bit differente in your site) with each line
When you found the line you will split it until you find the link inside the src=""
Reconstruct your tag with the host name on it: <img src="http://host.com" + link >
Then the image will appear ;)
Try using view.loadUrl(URL.toString()); instead of loadDataWithBaseURL

Android webview not displaying '%' character

I have a WebView using following code:
WebView webView = new WebView(cont);
webView.loadData("Red 20%", "text/html", "utf-8");
It is having trouble showing the string. But if I remove the '%' character from the string it is showing properly. What is wrong with the code? How do I display '%' in WebView?
Simple:
WebView webView = new WebView(cont);
webView.loadData("Red 20%", "text/html", "utf-8");
You can see the special characters here:
http://www.degraeve.com/reference/specialcharacters.php
URL encode the %
20%25 should do the trick
An easier alternative is to use TextUtils.htmlEncode() for the strings you want to display.
WebView webView = new WebView(cont);
String s = TextUtils.htmlEncode("Red 20%");
webView.loadData(s, "text/html", "utf-8");
Instead of % you have to useits equevalent to show it in web. actually it is &#37 so that your code should change to
webView.loadData("Red 20%", "text/html", "utf-8");
You can replace "Red 20%" -> "Red 20 %"

Categories

Resources