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