Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the SQLiteOpenHelper class do with the context parameter?

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?

like image 829
chessofnerd Avatar asked Jun 21 '12 23:06

chessofnerd


People also ask

What is the use of SQLiteOpenHelper class?

SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

What is difference SQLiteOpenHelper and SQLiteDatabase?

If it isn't already exist ofcourse. Difference between SQLiteOpenHelper and SQLiteDatabase close() is that SQLiteOpenHelper just closes inner instance of SQLiteDatabase. And it does it in thread safe way.

Which of the following must be overridden while using SQLiteOpenHelper class?

SQLiteOpenHelper provides callback methods and we should override it to get our job done. Those callback methods that we can override are onCreate(), onUpgrade(), onOpen() and onDowngrade(). And onCreate() and onUpgrade() are abstract methods and must be overridden.


1 Answers

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

like image 194
Frank Leigh Avatar answered Sep 28 '22 08:09

Frank Leigh