Login     Sign Up
Cyril Sermon (@admin)
10 months ago

SQLiteOpenHelper is an abstract class that wraps up the best practice pattern for creating, opening, and upgrading databases. By implementing and using an SQLiteOpenHelper, you hide the logic used to decide if a database needs to be created or upgraded before it’s opened.

The code snippet above shows how to extend the SQLiteOpenHelper class by overriding the construc-tor, 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 defi-nition. 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, current version, and a CursorFactory (if you’re using one).

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

A call to getWriteableDatabase can fail because of disk space or permission issues, so it’s good prac-tice to provide fallback to the getReadableDatabase method as shown below:

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 both cases, the get<read/write>ableDatabase call will return the existing, newly created, or upgraded database as appropriate.

Opening and Creating Databases without the SQLiteHelper

You can create and open databases without using the SQLiteHelper class with the openOrCreateDatabase method on the application Context.

Setting up a database is a two-step process. First, call openOrCreateDatabase to create the new data-base. Then, call execSQL on the resulting database instance to run the SQL commands that will create your tables and their relationships. The general process is shown in the snippet below:

private static final String DATABASE_NAME = “myDatabase.db”; private static final String DATABASE_TABLE = “mainTable”;

private static final String DATABASE_CREATE =

“create table “ + DATABASE_TABLE +

“ ( _id integer primary key autoincrement,” + “column_one text not null);”;

SQLiteDatabase myDatabase;

private void createDatabase() {

myDatabase = openOrCreateDatabase(DATABASE_NAME,

Context.MODE_PRIVATE, null);