Nacho L. Nacho L. - 1 month ago 11
Android Question

WebView not rendering correctly, displaying source code instead

I have an app with some Android 4.1/4.2 users reporting that a WebView isn't rendering its contents, but it is showing the source code instead.

The WebView display code is pretty standard, and it is working right for most users.

webView.setVisibility(View.VISIBLE);
webView.setVerticalFadingEdgeEnabled(false);
webView.setFadingEdgeLength(0);
webView.setFocusable(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!view.hasFocus()) {
view.requestFocus();
}
break;
}
return false;
}
});

WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setGeolocationEnabled(true);
settings.setLoadWithOverviewMode(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
settings.setAllowUniversalAccessFromFileURLs(true);
}
settings.setSupportZoom(true);

webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.w("TEST", url);
// The app does some other things here, but are unrelated to que question
return true;
}

});

webView.setWebChromeClient(new MyChromeClient());
webView.loadDataWithBaseURL(Const.WEB_VIEW_BASE_URL, injectHtmlAndCss(guide.getContent()), "text/html; charset=UTF-8", null, null);
}


And here is an example of what is happening for others:

HTML contents are not being rendered at all

I am completely clueless about this.

Answer

Turns out that the loadDataWithBaseURL method doesn't work well with Android 4.1/4.2.

I really needed the base url to be changed, because many assets were being referenced with relative routes in my HTML code, so I've injected in the HTML within the <head> tag a <base> tag. Example:

<html>
<head>
<base href="http://www.example.com/">
</head>
<body>
<!-- YOUR BODY GOES HERE -->
</body>
</html>

And I've loaded the html with loadData instead:

webView.loadData(injectHtmlAndCss(guide.getContent()), "text/html; charset=UTF-8", "UTF-8");

It worked like a charm. Phew.