private static final String TABLE_MAIN_CREATE = \"CREATE TABLE IF NOT EXISTS \" + TABLE_MAIN_NAME + \" ( a INTEGER, b LONG, c TEXT, d TEXT, e DATETIME, f TEXT)\";
pr
One way you can do inside onUpgrade
method is to drop the table and recreate it. This way, only the data for that particular table will be deleted and not the whole DB data.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("TAG", "Upgrading database from version " + oldVersion + " to " + newVersion);
switch (oldVersion)
{
case 1:
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MAIN_NAME);
db.execSQL(TABLE_MAIN_CREATE);
default:
break;
}
}
You need not call onCreate in onUpgrade. Doing db.execSQL(TABLE_MAIN_UPGRADE) in enough for update. Now you should clear data of your application. To do this re-install the app or execute in android shell
pm clear your.app.package
Caution: This is a good and working solution but there is are a lot of people who downvote this answer because they have something personal or because they don't know java's basics(case from 10 to 12 are without break;)
You have to do something depends on oldVersion
.
fx: you can have db versions from 10-14, the older then 10 you dont wana support and at every new version you add a new column the code should looks like(newVersion is 14) :
private static final String TABLE_MAIN_CREATE_14 =
"CREATE TABLE IF NOT EXISTS " + TABLE_MAIN_NAME +
" ( a INTEGER, b LONG, c TEXT, d TEXT, e DATETIME, f TEXT, g TEXT, h TEXT, i TEXT)";
private static final String TABLE_MAIN_UPGRADE_10_11 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column f TEXT";
private static final String TABLE_MAIN_UPGRADE_11_12 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column g TEXT";
private static final String TABLE_MAIN_UPGRADE_12_13 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column h TEXT";
private static final String TABLE_MAIN_UPGRADE_13_14 =
"ALTER TABLE " + TABLE_MAIN_NAME + " ADD Column i TEXT";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_MAIN_CREATE_14);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion){
case 10: // from 10 to 11 and go to next case
db.execSQL(TABLE_MAIN_UPGRADE_10_11);
case 11: // from 11 to 12 and go to next case
db.execSQL(TABLE_MAIN_UPGRADE_11_12);
case 12: // from 12 to 13 and go to next case
db.execSQL(TABLE_MAIN_UPGRADE_12_13);
case 13: // from 13 to newVersion
db.execSQL(TABLE_MAIN_UPGRADE_13_14);
break;
default:
//not upgratable too old - so we should drop and recreate;
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MAIN_NAME );
onCreate(db);
break;
}
}
In Android Documentation:
This method is called after the database connection has been configured and after the database schema has been created, upgraded or downgraded as necessary.
onCreate(db); is not necessary for upgrade your database.