My following code loads html-content from a Url and displays it in the webview:
MainActivity.java
String htmlContent = getHtmlContent();
if (htmlContent != null) {
webView.getSettings().setBuiltInZoomControls(true);
webView.loadData(htmlContent, fileType.endsWith("rfc822") ? "rfc822" : "text/html", "UTF-8");
}
getHtmlContent Method
DownloadTask task = new DownloadTask();
try {
String result = String.valueOf(task.execute(currentFileUrl).get());
if (task.getStatus() == AsyncTask.Status.RUNNING) {
loadingProgressBar.setVisibility(View.GONE);
}
return result;
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return null;
and the DownloadTask.java class
public class DownloadTask extends AsyncTask<String, Void, StringBuilder> {
@Override
protected StringBuilder doInBackground(String... urls) {
StringBuilder result = new StringBuilder();
URL url;
HttpURLConnection connection;
try {
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result.append(current);
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
One problem that I had is the WebView wasn't desplaying the content, I solved it by setting WebView webview = findViewById(R.id.webView);
and removing webview = new WebView(this);