Yurii
Yurii

Reputation: 675

How i can onUpgrade me database in Android

Can you help me? I want to upgrade my database in application. I need to create new column by name "alarm". How i can do it in method onUpgrade()? p.s in google i dont found needed information. and how to save the information with old database to new database

My code:

public static final String DB_NAME = "database.db";
public static final int DB_VESION = 1;
public static final String ID_COLUMN = "_id";
public static final String NOTE_COLUMN = "note";
public static final String DATE_COLUMN = "date_create";
public static final String STATE_COLUMN = "state";
public static final String DAY_STATE_COLUMN = "day_state";
public static final String ALARM_COLUMN = "alarm";
public final String[] allColumns = {ID_COLUMN, DATE_COLUMN, NOTE_COLUMN, STATE_COLUMN, DAY_STATE_COLUMN};
public static final String TABLE_NAME = "notes";

@Override
public void onCreate(SQLiteDatabase db) {
final String CREATE_DB = "CREATE TABLE " + TABLE_NAME + " (" +
ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT," +
DATE_COLUMN + " LONG  NOT NULL," +
NOTE_COLUMN + " VARCHAR(140) NOT NULL," +
STATE_COLUMN + " INTEGER NOT NULL," +
DAY_STATE_COLUMN + " LONG" +
");";
db.execSQL(CREATE_DB);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
//how i can do this????
onCreate(db);
}

thanks in advance

Upvotes: 1

Views: 128

Answers (3)

Yurii
Yurii

Reputation: 675

the code in method onUpgrade may be like this??

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { for (int i = oldVersion; i < newVersion; i++) { switch (i) { case 2: String createAlarmColum = "ALTER TABLE notes ADD COLUMN alarm INT;"; db.execSQL(createAlarmColum); ForgetLogManager.showAppLog(createAlarmColum); break; } } }// onCreate(db);

Upvotes: 0

Jonatan Collard Bovy
Jonatan Collard Bovy

Reputation: 558

My guess is that you're extending the SQLiteOpenHelper class, to be able to manage your DB.

If that's the case, the constructor's last param is the DB_VERSION. You should increase that number, so that onUpgrade get's called. But be aware that every time you change your DB_VERSION, the onUpgrade method will be called so i'd advice to use a switch to identify each DB upgrade you need to do. Otherwise, you might find yourself trying to add a column that already exists.

If you're looking for the code to add a column, try something like this:

String createAlarmColum = "ALTER TABLE notes ADD COLUMN alarm INT;";
db.execSQL(createAlarmColum);

Hope it helps :)

Upvotes: 0

laalto
laalto

Reputation: 152807

Since you have already chosen to drop and recreate the table, just add the new column specification to the CREATE TABLE in your onCreate().

Increment your DB_VESION so that onUpgrade() gets called.

Upvotes: 1

Related Questions