Extend SQLiteOpenHelper as a singleton class in Android

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;
		}
	}
Advertisements

About cmanios

programming
This entry was posted in Android, Databases and tagged , , , , . Bookmark the permalink.

7 Responses to Extend SQLiteOpenHelper as a singleton class in Android

  1. Buz says:

    Hi there – can you give me a little guidance here? I’m thinking of using the same Singleton idea for a SQLiteOpenHelper – my question is – once you’ve got your writable/readable database and performed your SQL operations, do you call db.close()? Or, because it’s a singleton, do you essentially leave it open until the app finishes? Can you give an example method that uses your singleton to get a writable database and do some work on it? Thanks

    • cmanios says:

      Hi Mark,
      There are 2 possibilities:
      1. You subclass Aplication object and store db object there. You can call db.close() when you app finishes.
      2. You create DatabaseHelper for every activity and call db.close() in onPause() or in onStop() events

  2. Francis Xavier says:

    Hello, I am using your example and call the getWritableDB() from the singleton class, Do I need to call the close too?? Or it automatically gets called when we close the app?

    • cmanios says:

      Close() is automatically called when the entire application is killed. But if you use this class in many activities or threads you should call close() in order to avoid leaks.

  3. Tony says:

    In your program, you din’t use getApplicationContext ,
    mInstance = new DatabaseHelper(context.getApplicationContext() );

  4. Since, in getInstance() we get just one instance of database. So, is using *if ((myWritableDb == null) || (!myWritableDb.isOpen())) { myWritableDb = this.getWritableDatabase(); }* necessary? Can’ get just go without having this definition for getWritableDatabase() with singleton instance?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s