6

I am extending the SQLiteOpenHelper class. My constructor is

public MyDatabaseHelper(Context context) {
    super(
        context,         // ???
        "MyDatabase.db", // Database name
        null,            // Cursor factory
        1                // database version
    );
}

What does the SQLiteOpenHelper constructor do with the context information?

For my application, the constructor will behave the same regardless of the program state (context). Can I pass null in for the context with out any future problems?

1 Answer 1

6

If you supply a null value, it will create an in-memory database instead but you'll need to supply null for the database name parameter as well so it's handled properly.

This is documented in the constructor documentation for context

context to use to open or create the database name of the database file, or null for an in-memory database

Also, if you view the source code of the SQLiteHelper class itself, you will see it uses the mName value to decide whether to use mContext. View the source code online here:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.4_r1.2/android/database/sqlite/SQLiteOpenHelper.java#SQLiteOpenHelper.0mContext

4
  • 1
    Thank you! This makes more sense now. I had never heard of grepcode and I think that site and I will become well acquainted! Commented Jun 22, 2012 at 3:07
  • rookie question: isn't the database name already being used for the second parameter? What would go in for the context then?
    – AlleyOOP
    Commented Dec 26, 2013 at 20:09
  • The context can be the activity or the application itself. Commented Dec 31, 2013 at 0:37
  • From the source code: context is used for: 1) get full path of the db. 2) invoke openOrCreateDatabase on context object. Commented Jul 21, 2016 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.