Android WebView with garbled UTF-8 characters.
I'm using some webviews in my android app, but are unable to make them display in utf-8 encoding.
If use this one I won't see my scandinavian charcters:
mWebView.loadUrl("file:///android_asset/om.html")
And if try this one, I won't get anything displayed at all
mWebView.loadDataWithBaseURL("file:///android_asset/om.html", null, "text/html", "utf-8",null);
Regards
You can try to edit the settings of your webview before you load the data:
WebSettings settings = mWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
Also, as provided in the comment below, be sure to add "charset=utf-8"
to the loadData call:
mWebView.loadData(getString(R.string.info_texto), "text/html; charset=utf-8", "utf-8");
This seems to have 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
Recent versions of Android
Some are reporting a change in the behavior of the loadData calls requiring the mimeType
to include charset=utf-8
.
webView.loadData(scandinavianCharacters, "text/html; charset=utf-8", "UTF-8");
You can also use this formulation with WebSettings
WebView webView = (WebView) findViewById(R.id.DemoWebView);
WebSettings webSettings = webView.getSettings();
webSettings.setDefaultTextEncodingName("utf-8");
webView.loadData(scandinavianCharacters, "text/html; charset=utf-8", null);
It is amazing that Android still hasn't resolved this basic issue.
Derzu's bit is very helpful above:
webview.loadData(getString(R.string.info_texto), "text/html; charset=utf-8", "utf-8");
I had UTF-8 on Android 2.x and garbled ANSI on 4.x until I put in the
charset=utf-8
in the wv.loadUrlWhatever()
call. Excellent attention to detail, Derzu