4

In my android application i have created the database which contains some data and it is on the app store.Now i need to change the database according to new requirement. when i update the apk file it wont create the new db again because it is already created.

How can i update the database which is already created on users device? How can i call the onUpgread() method of sqlite db? And is there any way to check it on emulator?
Please suggest.Thanks in advance.

 @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME );

      onCreate(db);

}

2 Answers2

4

The onUpgrade method is called automatically if the database version has been increased.

When you create a database you supply a version number as an integer to the constructor. Eg.

public class DatabaseHelper extends SQLiteOpenHelper{

static final String dbName = "myDatabase";
static int dbVersion = 3;

    public DatabaseHelper(Context context) {
        super(context, dbName, null, dbVersion);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Create database
    }

If you increase dbVersion above, when the database is created again it will see that the number has increased because it keeps track of the current version number you send through. An increase in the value will trigger onUpgrade and run through that code.

In your onUpgrade method you can specify what to do between different version numbers. For example, there might be a change to the database that is made between version 2 and 3, but also between 3 and 4, in which case you need to handle people who will be jumping from 2 straight to 4, who do not update their APK files as often as you the developer might like!

A simple way of doing this is using if statements, and updating the database in order, so processing upgrades chronologically.

biddulph.r
  • 5,226
  • 3
  • 32
  • 47
  • ok.But how do i check this on emulator..I want to be sure.Is there any way to check this.Please suggest – picaso_is_back Sep 21 '12 at 09:42
  • If you want to check it on the emulator, load your application up with the previous version of the database, make sure the database gets initialised, and then change the database version number, add in the code to onUpgrade, and load the application again with this new code and version number. If you put a breakpoint in onUpgrade you will see it being hit, and it will run through the code, updating your database in the same way updating with a new APK would on a device – biddulph.r Sep 21 '12 at 11:01
1

Increase your DATABASE_VERSION for upadting database. When you increase your database version at that time onUpgrade method is called.

Chirag
  • 56,621
  • 29
  • 151
  • 198