Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Learning Android: WebView character encoding

DZone's Guide to

Learning Android: WebView character encoding

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

In my continued attempts to learn how to write an Android application I came across a problem with character encoding when trying to load some text into a WebView.

I was initially trying to write the text to the WebView like this:

WebView webview = new WebView(collection.getContext());
webview.loadData(textWithQuotesIn, "text/html", "UTF-8");

 

 

But ended up with the output in the picture on the left hand side. I tried playing around with the encoding and debugged the application all the way through until it hit the WebView but there didn’t seem to be any problem with the text.

I eventually came across a post on StackOverflow where mice suggested using one of the other methods available for writing to a WebView.

I changed my code to read like this:

WebView webview = new WebView(collection.getContext());
webview.loadDataWithBaseURL(url, textWithQuotesIn, "text/html", "UTF-8", url);

And now the single quotes are rendering correctly as can be seen on the image on the right.

I had a quick look at the Android source code to see if there was any obvious reason why one of the methods would work and the other wouldn’t but I couldn’t see anything.

Perhaps I’m doing something wrong with my call to ‘loadData’ and that’s why it’s not rendering the character set correctly. If that’s the case please let me know.

 

From http://www.markhneedham.com/blog/2011/12/27/learning-android-webview-character-encoding

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}