Extend SQLiteOpenHelper as a singleton class in Android

1 minute read

Update: 2012-07-27

Today I wanted to keep my DatabaseHelper class unique and public in all my activities. Till now I kept creating and destroying a DatabaseHelper object for each Activity I was bringing in foreground. Thanks to Konstantinos Vaggelakos post (Database SQLiteOpenHelper singleton class for Android) I added the following code to my class and now I have a singleton class which helps me to access my database.

It is useful to keep only one reference to an open writabe SQLiteDatabase object, so I added myWritableDb as a member and the method getMyWritableDatabase() which returns the same writable database object every time.

Now we have a SQLiteDatabase object as a class member and we do not want to forget it open and leak. So we override onClose() method and close it manually.

public class DatabaseHelper extends SQLiteOpenHelper {

	private final Context myContext;
	private static DatabaseHelper mInstance;
	private static SQLiteDatabase myWritableDb;

	/**
	 * Constructor takes and keeps a reference of the passed context in order to
	 * access to the application assets and resources.
	 *
	 * @param context
	 *            the application context
	 */
	private DatabaseHelper(Context context) {

		super(context, DB_NAME, null, 1);
		this.myContext = context;
	}

	/**
	 * Get default instance of the class to keep it a singleton
	 *
	 * @param context
	 *            the application context
	 */
	public static DatabaseHelper getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new DatabaseHelper(context);
		}
		return mInstance;
	}

	/**
	 * Returns a writable database instance in order not to open and close many
	 * SQLiteDatabase objects simultaneously
	 *
	 * @return a writable instance to SQLiteDatabase
	 */
	public SQLiteDatabase getMyWritableDatabase() {
		if ((myWritableDb == null) || (!myWritableDb.isOpen())) {
			myWritableDb = this.getWritableDatabase();
		}

		return myWritableDb;
	}

	@Override
	public void close() {
		super.close();
		if (myWritableDb != null) {
			myWritableDb.close();
			myWritableDb = null;
		}
	}

Leave a Comment