Extend SQLiteOpenHelper as a singleton class in Android

UPDATE!

Post has moved to https://manios.org/2012/05/17/extend-sqliteopenhelper-as-a-singleton-class-in-android

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s