Wednesday, 1 October 2014

why we need to onUpgrade() method in SQLiteOpenHelper class?

onUpgrade is basically for handling new db changes (could be new columns addition,table addition) for any new version app.

Draping the table is not always necessary in on Upgrade it all depends on what your use case is. if the requirement is to not to persists the data from your older version of app then drop should help, but if its like changing schema then it should only have alter scripts.

When implementing the SQLiteOpenHelper, you pass a version parameter to the superclass constructor. This should be a static value you can change in future versions of your application (usually you'd want this to be a static final attribute of your SQLiteOpenHelper implementation, alongside the database name you pass to the superclass constructor).
Then, when you want to upadte the database, you increment the version parameter that will be used in your SQLiteOpenHelper implementation, and perform the SQL modifications you intend to do, programmatically, inside the onUpgrade method.
Say your DB started with table A in version 1, then you added table B in version 2 and table C in version 3, your onUpgrade method would look like:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) { // do stuff for migrating to version 2
        db.execSQL( ...create table B... );
    }
    if (oldVersion < 3) { // do stuff for migrating to version 3
        db.execSQL( ...create table C... );
    }
}
When the superclass constructor runs, it compares the version of the stored SQLite .db file against the version you passed as a parameter. If they differ, onUpgrade gets called.
I should check the implementation, but I assume onUpgrade is also called after onCreate if the database needs to be created, and there's a way to ensure all of the upgrades are executed (for example, by forcing all version numbers to be positive integers and initializing a newly created database with version 0).