Introducing the SQLite OpenHelper

SQLiteOpenHelper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases. By implementing an SQLite Open Helper you hide the logic used to decide if a database needs to be created or upgraded before it's opened.

Listing 7-1 showed how to extend the SQLiteOpenHelper class by overriding the constructor, onCreate, and onUpgrade methods to handle the creation of a new database and upgrading to a new version, respectively.

In the previous example onUpgrade simply drops the existing table and replaces it with the new definition. In practice, a better solution is to migrate existing data into the new table.

To use an implementation of the helper class, create a new instance, passing in the context, database name, and current version, and a CursorFactory (if you're using one).

Call getReadableDatabase or getWritableDatabase to open and return a readable/writable instance of the underlying database.

A call to getWritableDatabase can fail because of disk space or permission issues, so it's good practice to provide fallback to the getReadableDatabase method, as shown in Listing 7-2.

LISTING 7-2: Using the SQLiteOpenHelper to access a database Available for downloadon dbHelper = new myDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION);

SQLiteDatabase db; try {

db = dbHelper.getWritableDatabase();

catch (SQLiteException ex){

db = dbHelper.getReadableDatabase();

Behind the scenes, if the database doesn't exist the helper executes its onCreate handler. If the database version has changed, the onUpgrade handler will fire. In either case the get<read/writ>ableDatabase call will return the existing, newly created, or upgraded database, as appropriate.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment