Showing static HTML in WebView - Android
By admin
Loading a live web page from the internet into Webview object is straight forward.
The simplest way is to create a Webview object and load URL into the object:
<pre class="lang:java decode:true ">webview.loadUrl("http://your-website.com/");
But what if you need to show a custom HTML page to your users?
For a simple static page you can create a HTML document in a string variable and load it into Webview object:
<pre class="lang:java decode:true ">String welcome = "Welcome <em>John</em>!";
webview.loadData(welcome, "text/html", null);
This is cool but what if you need to have a more complex HTML page with CSS blocks?
In that case you need to have a HTML file and store it in your project asset folder.
You need to use ‘loadDataWithBaseURL()’ method instead to provide webView with asset folder as base URL (where data
is content of HTML file) :
<pre class="lang:java decode:true ">webview.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "utf-8", null);
You can read content of HTML file from asset folder and save it into a String variable (data) and pass it to loadDataWithBaseURL method.
Below method is just one way of reading a file content into a variable:
<pre class="lang:java decode:true ">public String fetchHTML() {
StringBuilder sb = new StringBuilder();
String tmpStr = "";
try {
InputStream is = Context.getAssets().open("static.html");
BufferedReader bfr = new BufferedReader(new InputStreamReader(input, "UTF-8"));
while ((tmpStr = bfr.readLine()) != null) {
sb.append(tmpStr);
}
in.close();
} catch (IOException e) {
// Catch any IO exception here
}
return sb.toString();
}