Tim Tim - 26 days ago 8
Java Question

SQLiteOpenHelper - how is the database created?

I'm making a database application, and my program works and I've understood most of the tutorial I've been following. However, one aspect remains unclear to me.

There is an inner class of MyDBHelper extending SQLiteOpenHelper. Outer variables include the SQLiteDatabase called d. The code for the MyDBHelper is:

private static class MyDBHelper extends SQLiteOpenHelper {
MyDBHelper(Context c) {
super(c, DB_NAME, null, DB_VERSION);

public void onCreate(SQLiteDatabase db) {
try {
} catch (SQLException e) {

public void onUpgrade(SQLiteDatabase db, int oldVers, int newVers) {
Log.w(TAG, "Upgrading database from version " + oldVers + " to " + newVers + ", which will destroy all old data.");

My question is how does this actually create the initial database. It occurs in the onCreate() method, but as far as I can see, this is never called. I understand that it is called when the database is created for the first time, but where? And furthermore, how is it passed a SQLiteDatabase db? I haven't passed any database to the method. And how is my SQLiteDatabase db variable from the outer class set to the created database? Could someone talk me through this like an idiot?

Answer Source

onCreate() and onUpgrade() methods are really called the first time when Db is created. In facts, it's checked in getReadableDatabase() or getWritebleDatabase() methods of SQLiteOpenHelper. It will check if the DB already exist on the data directory and what is it's version. According to this it will either call onCreate(), or onUpgrade(). Or nothing, if db file exist and of correct version.

You can search your code for executing myDBHelper.getReadable(Writable)Database(). That is the time when this check will be performed.

Please let me know if more details are needed. Good luck