Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView incorrectly handling newlines in preformatted text

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.

like image 775
Axarydax Avatar asked Feb 17 '11 09:02

Axarydax


3 Answers

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);
}
like image 92
Mike Avatar answered Nov 18 '22 11:11

Mike


Try this:

webView.loadDataWithBaseURL(...)

More info here

like image 28
Jigish Chawda Avatar answered Nov 18 '22 11:11

Jigish Chawda


Also you can use

chapterWebView.loadDataWithBaseURL("file:///android_asset/NTImages/", message.replaceAll("\\n", "<br/>") , "text/html", "utf-8", "utf-8");
like image 30
Bahaa Hany Avatar answered Nov 18 '22 12:11

Bahaa Hany