I am writing this blog to add columns in our database table which would compatible with old version of database.
Here I use Alter Table command on my onUpgrade() method where I make condition for the database version.
We can add only one column at a time so we break it into multiple ALTER TABLE command.
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "Reader.db";
private static final String TIMESTAMP = " TIMESTAMP";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_QUERY =
"CREATE TABLE IF NOT EXISTS table (" +
"id" + " INTEGER PRIMARY KEY" + COMMA_SEP +
"image1" + " TEXT_TYPE " + COMMA_SEP +
"image2" + " TEXT_TYPE " + COMMA_SEP +
"image3" + " TEXT_TYPE " + COMMA_SEP +
"name" + " TEXT_TYPE " + COMMA_SEP +
"isuploaded" + " INTEGER" + COMMA_SEP +
"createdate" + " TEXT_TYPE" +
")";
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_QUERY);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
try {
if (oldVersion < 2) {
db.execSQL("ALTER TABLE table ADD image2 TEXT ");
db.execSQL("ALTER TABLE table ADD image3 TEXT ");
db.execSQL("ALTER TABLE table ADD name TEXT ");
saveDATA();
}
} catch (Exception e) {
e.printStackTrace();
}
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
1 Comment(s)