onUpgrade database - oldVersion - newVersion onUpgrade database - oldVersion - newVersion sqlite sqlite

onUpgrade database - oldVersion - newVersion


// Do you need this?private static int DATABASE_VERSION = 2;

Yes, you need this. (Even better, make it final too.)

This tells the database helper what the latest version of the database schema is. This should be fixed in your app code, and incremented whenever you alter the schema.

When your app starts up, the helper does a check at runtime that your code's idea of the latest version is the same as the version which was active when the database was last created or upgraded. (This is what db.getVersion() is for.) If the numbers don't match, then the helper knows that the stored database is out-of-date with respect to your application code, and so it runs the upgrade routine.

It looks as if you're not creating the database from scratch, but importing an existing database from your assets. When you do this initial import, this is the time at which to make sure the stored version matches your code's version; either apply it directly to the database file in your assets, or, if you're sure the database file in your assets matches the code, then you call setVersion(DATABASE_VERSION).

In any case, you shouldn't be trying to modify the version numbers in the onUpgrade() routine. This is only ever called if the versions don't match, and all you're supposed to do here is make whatever changes are needed to bring the database up-to-date. The helper will manage the storing of the new version number once the upgrade is complete.


Adding some info to Graham Borland answer.I will explain with the scenario of application in which your database is in asset folderand you copy it to to your package folder if its not already present there.Now if you want to upgrade your app with updated database.you need to set

 private final static int DB_VERSION=2;          // Database Version

in your Database helper class.

(Any integer which should be more than initial db version which you set initialy in this class)

After that you need to add code for override onUpgrade()In this scenarion I overrite old db with latest.You may change your code as your liking

@Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        // TODO Auto-generated method stub          CopyNewDatabaseFromAsset();    } 

If you need any explanation please post in comment :)