Over a million developers have joined DZone.

Learning Android: WebView character encoding

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}