Alex K
Alex K

Reputation: 5212

[android]How to add new column to DB on missing one?

I wrote an application in android that using DB. In the next version I want to add new column to the DB but without re-installing the application. How can I upgrade the table on missing column exception?

Upvotes: 2

Views: 71

Answers (2)

user3506595
user3506595

Reputation: 139

You can simply do it by changing(increment) database version

public class Databas extends SQLiteOpenHelper {
  private static final int DATABASE_VERSION = 2;
Database(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  if(oldVersion <= DATABASE_VERSION)
        db.execSQL("//write table altering query here ");
    onCreate(db);


}

increment database version value with 1 from your current database version value

Upvotes: 1

edisonthk
edisonthk

Reputation: 1423

This can be easily done by using SQLiteOpenHelper. Let say your current database version is 1. You just change it to 2. Then if there is any version 1 database will be automatically update to version 2 and onUpgrade method will be invoked.

private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(oldVersion <= 1)
            db.execSQL("Do you table alter here ");
        onCreate(db);
    }
}

Upvotes: 1

Related Questions