Is the onUpgrade method of SQLiteOpenHelper ever called? If so, when is it called and by what? If it is not called by the developers, then why is it there? What really happe
It is actually called when you call getReadableDatabase
or getWritableDatabase
.
Deep dive:
You pass version number in the constructor of SQLiteOpenHelper
which is stored in a variable called mNewVersion
. That's it. Nothing happens at this point.
Everytime you call getReadableDatabase or getWritableDatabase, it will call a method called getDatabaseLocked
. This method will get the existing version number of the database and compare it with the mNewVersion
.
onCreate
onUpgrade
. What should I write in onCreate and onUpgrade ?
onCreate
should contain the code that creates a schema for the first time.
You can leave onUpgrade
empty first time since it won't be called the first time. When you want to change the table structure at later stage, that code should go in here.
SQLiteOpenHelper.java(Source code)
public SQLiteDatabase getWritableDatabase() {
synchronized (this) {
return getDatabaseLocked(true);
}
}
public SQLiteDatabase getReadableDatabase() {
synchronized (this) {
return getDatabaseLocked(false);
}
}
private SQLiteDatabase getDatabaseLocked(boolean writable) {
.
.
final int version = db.getVersion();
if (version != mNewVersion) {
if (db.isReadOnly()) {
throw new SQLiteException("Can't upgrade read-only database from version " +
db.getVersion() + " to " + mNewVersion + ": " + mName);
}
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
if (version > mNewVersion) {
onDowngrade(db, version, mNewVersion);
} else {
onUpgrade(db, version, mNewVersion);
}
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
onOpen(db);
}