Kyle Banks

Using an HTML5 Database in Your Android Application

Written by @kylewbanks on Feb 18, 2013.

A common method of developing HTML5 applications for Android is to implement a native WebView and have it load your HTML5 web page. Using this method, the user is presented with what looks like a native application, because the 'browser' used to render your HTML does not have any of the standard browser buttons or the URL input. It simply loads your HTML with no other UI elements.

If you don't want to require internet access in your app, you can easily package the HTML/CSS/JavaScript/images/etc with your Android app, and have them run locally on the user's device. This works great, because you don't need to rely on slow mobile internet connections to load your web pages. Doing this is very straightforward, as shown below:

public class MyActivity extends Activity {
    WebView webView = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Get rid of the android title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        webView  = (WebView) findViewById(R.id.main_webview);
        WebSettings settings = webView.getSettings();

	 //Enable Javascript
        settings.setJavaScriptEnabled(true);

        webView.loadUrl("file:///android_asset/index.html");
     }
}

This does a few simple things. First, it removes the app title bar from the top of the view. Second, we enable JavaScript which is disabled by default. Finally, we load index.html which should be located in the assets directory in the root of your application. When the user loads this application, they will simply see index.html, without URL's or browser buttons. Done properly, this can easily look like a native application.

One common element of any application though, is a requirement for data storage. So how is this accomplished without internet access? The HTML5 database API, of course!

Preparing Android For the Database

Implementing and HTML5 database is very straightforward, but there are a few things you need to do with your WebView component before it will allow you to do so in an Android app.

First, we need to tell Android where to store the database and we need to tell it that the database should persist once the application has closed (otherwise, each time the user closes the application, the database will be lost). The second bit of functionality we need to implement is to handle the case where the database may have exceeded its maximum size. When this happens, we should increase the size of the database to make sure data is not lost.

Here is the updated code:

public class MyActivity extends Activity {
    WebView webView = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Get rid of the android title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        webView  = (WebView) findViewById(R.id.main_webview);
        WebSettings settings = webView.getSettings();

	//Enable Javascript
        settings.setJavaScriptEnabled(true);
		
	//Enable DOM storage, and tell Android where to save the Database
     	settings.setDatabasePath("/data/data/"+this.getPackageName()+"/databases/");
        settings.setDomStorageEnabled(true);

        webView.loadUrl("file:///android_asset/index.html");
		
     	webView.setWebChromeClient(new WebChromeClient() {
		
	    	/** Called when the database exceeds it's maximum size **/
	    	@Override
	    	public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
			//Double the estimated size of the Database
		       quotaUpdater.updateQuota(estimatedSize * 2);
		} 
        });
    }
}

Now we can go ahead and execute the JavaScript to access our database:

var myDB = window.openDatabase(DB_name, DB_version, DB_displayName, DB_sizeEstimate);

if(myDB != null) {
	/* Ready to go! */
} else {
	/* The WebView is not giving access to the Database, something isn't configured properly */
}

Assuming you followed the above steps, you should be good to go with your database!

Let me know if this post was helpful on Twitter @kylewbanks or down below!