1

I'm new at Android and database, I have this method in DatabaseIncomeOutcome.java class:

public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_IO + " TEXT NOT NULL, " +
        KEY_NOTE + " TEXT NOT NULL);"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }

}

public DatabaseIncomeOutcome(Context c){
    ourContext = c;
}

public DatabaseIncomeOutcome open(){
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;

when I called the method from another class

            DatabaseIncomeOutcome entry = new DatabaseIncomeOutcome(this);
            entry.open();

How and when the onUpgrade called? Is it called everytime I execute the entry.open()?

I also want to add this script

if (newVersion > oldVersion) {
    db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");

on onUpgrade to add new Column,

Then, how I should call the `onUpgrade', so I could add new column, if I might need it for future development.

Thanks...

dmon
  • 30,048
  • 8
  • 87
  • 96
Tutompita
  • 639
  • 1
  • 5
  • 14

1 Answers1

4

The way onUpgrade method is called for an android Database is based on the DATABASE_VERSION you pass, when the version of your next code is different than the one currently installed THEN the onUpgrade will be called, giving you the chance to change things on your database schema...

Note that this method is not something you manually force to be called, it will be automatically called by the OS when the event explained above happens...

Regards!

Martin Cazares
  • 13,637
  • 10
  • 47
  • 54
  • 1
    Thanks... It is worked!!! I have also find out from http://stackoverflow.com/questions/7647566/why-is-onupgrade-not-being-invoked-on-android-sqlite-database that onUpgrade executed from SQLiteOpenHelper.getWritableDatabase()... And it triggered when we change DATABASE_VERSION value... – Tutompita Jun 07 '13 at 22:03