Displaying Static HTML Content in Android WebView

Basic WebView Implementation

Loading a live web page from the internet into WebView object is straightforward.
The simplest way is to create a WebView object and load URL into the object:

1
webview.loadUrl("http://your-website.com/");

Loading Custom HTML Content

Simple HTML String

For a simple static page you can create a HTML document in a string variable and load it into WebView object:

1
2
String welcome = "Welcome <em>John</em>!";
webview.loadData(welcome, "text/html", null);

Complex HTML with CSS

For more complex HTML pages with CSS blocks, 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):

1
webview.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "utf-8", null);

Reading HTML from Assets

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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();
}