Reputation: 1168
I am learning SQLite database in android, as I know, we normally use the pattern below (see the code snippet), my understanding is that
NoteDbHelpe
obj is instantiated, the constructor is
called, it will check if the corresponding database is created. onCreate
to create the tables. 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
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/oronOpen(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