I am learning to use Sqlite on Android by using this tutorial. I am having trouble understanding some of the code.
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
I make a new object of DatabaseHandler in my activity. The super in the constructor is SQLiteOpenHelper constructor. The code works great, it creates a new database, if there is none and it uses the old one if it exists. I would like to make some changes to this code(I want to add different tables to one db), but I dont understand how exactly does this work, how does the constructor know if it should create a new db or use the existing one?
The trick is that your class extends SQLiteOpenHelper, the call to super
in your constructor triggers a lot of behind-the-scenes code.
If you read through the SQLiteOpenHelper source code you'll see that getWritableDatabase()
and getReadableDatabase()
call the same method: SQLiteOpenHelper#getDatabaseLocked()
. This method does most of the work. It is the one that determines whether a database needs to be created, opened, upgraded, or anything else, from the information that you supplied in one simple command: super(context, DATABASE_NAME, null, DATABASE_VERSION);
.