Question

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);

}
Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top