rjr-apps
rjr-apps

Reputation: 318

How to do Character Encoding in a WebView?

I have an app in which there are several WebViews, each displaying a paragraph of description text. Almost all of them have garbled characters in them, usually where there are single quotes or double quotes.

For example, a string which should look like the following:

Body ‘N’ Space

Ends up looking like this in the WebView:

Body ÂNÂ Space

Here's what I first tried:

textWebView.loadData(getHtmlDescription(), "text/html", "UTF-8");

I ended up trying many solutions, including the following:

Adding this before loadData:

WebSettings webSettings = textWebView.getSettings();
webSettings.setDefaultTextEncodingName("UTF-8");

Changing loadData to loadDataWithBaseURL:

WebSettings webSettings = textWebView.getSettings();
webSettings.setDefaultTextEncodingName("UTF-8");
textWebView.loadDataWithBaseURL(null, getHtmlDescription(), "text/html", "UTF-8", null);

Changing "text/html" to "text/html; charset=UTF-8":

WebSettings webSettings = textWebView.getSettings();
webSettings.setDefaultTextEncodingName("UTF-8");
textWebView.loadDataWithBaseURL(null, getHtmlDescription(), "text/html; charset=UTF-8", "UTF-8", null);

And unfortunately, none of those solutions did the trick!

Upvotes: 0

Views: 658

Answers (1)

rjr-apps
rjr-apps

Reputation: 318

After trying all those solutions without success, I ended up trying to just find and replace all the bad characters I could see. That was just too cumbersome and inefficient, but somehow I stumbled on the following two-line fix that did the job for all of it!

In my getHtmlDescription() method, I added these two lines:

description = description.replace("Â", "");
description = Html.fromHtml(description, Html.FROM_HTML_MODE_LEGACY).toString();
return description;

Upvotes: 1

Related Questions