Zhi Wang
Zhi Wang

Reputation: 1168

When is the SQLite database created?

I am learning SQLite database in android, as I know, we normally use the pattern below (see the code snippet), my understanding is that

  1. When the NoteDbHelpe obj is instantiated, the constructor is called, it will check if the corresponding database is created.
  2. If not, create the database and call the onCreate to create the tables.
  3. If yes, see if we need to upgrade the database, if yes, call the onUpgrade.

My main concern is about when the database is created, I think it should be handled in the constructor, does my understanding correct?

    public class NoteDbHelper extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "notes_db";

    public NoteDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

     public void onCreate(SQLiteDatabase db) {
         String createNoteTableSql = "CREATE TABLE ...";
         db.execSQL(createNoteTableSql);
     }

    @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
         db.execSQL("DROP TABLE IF EXISTS " + NOTE_TABLE_NAME);

        // Create tables again
        onCreate(db);
    }

Upvotes: 0

Views: 81

Answers (2)

Mattias Buelens
Mattias Buelens

Reputation: 20159

No, the database is not created when the helper is constructed. Instead, it is opened (and created if needed) when it is first used. The documentations are very clear about this:

public SQLiteDatabase getWritableDatabase ()

Create and/or open a database that will be used for reading and writing. The first time this is called, the database will be opened and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and/or onOpen(SQLiteDatabase) will be called.

The reasoning for this is in the class overview:

This class makes it easy for ContentProvider implementations to defer opening and upgrading the database until first use, to avoid blocking application startup with long-running database upgrades.

Upvotes: 3

kriomant
kriomant

Reputation: 2326

Just view source

onCreate is called from getDatabaseLocked which is called from getWritableDatabase and getReadableDatabase.

Upvotes: 2

Related Questions