When does OnUpgrade get called and how does it get the oldVersion parameter?

Snake picture Snake · Jan 17, 2013 · Viewed 8.8k times · Source

I am working on an update for my current app. My app use SQLite DB and so far I am at version 1. I will need to alter/introduce new tables in my second version. I did my research and I found that to do that the best way is to have switch(case) statements in which I do the updates to db in a fall-through manner.

My question is, how does android know what is the older version in the onUpgrade()?. In fact, when does it get called?.

So for the users who are downloading my updated app for first time, I assume the onUpgrade() will not be called! How would android know when not to call onUpgrade()?

Please clarify this for me. I want to submit my first update and I don't want to lose my hard-earned users :)

Answer

Martín Valdés de León picture Martín Valdés de León · Jan 17, 2013

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 update 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).