Roonil
Roonil

Reputation: 536

Correct way to use onUpgrade when not updating tables?

I just finished making my first android app. Currently the database helper contains this method:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+SUBJECTS_TABLE_NAME);
    onCreate(db);
}

After some googling I'm getting contradictory information about what exactly I should put in this method. When I update the app I don't want to change the database, and I think this method will currently erase user data? What is the best way to run an update that doesn't change any of the database?

Upvotes: 0

Views: 139

Answers (3)

user8959091
user8959091

Reputation:

This method will be invoked only if you change the version of the database not your app.
You can make as many upgrades/updates to your app as you want. As long as the version of the database remains the same you have nothing to fear.
In your DatabaseHelper(or whatever name you gave) class's constructor there is a parameter int version. When you instantiate this class you pass the version of your db.
If you change the version from 1 to 2 then onUpgrade() will be invoked.

Upvotes: 2

user3586826
user3586826

Reputation: 158

private int DATA_BASE_VERSION=100;

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
   if(oldVersion<100){
      //your data base need an alter table or something new you added
   }
}

Now if you want to change it again

private int DATA_BASE_VERSION=101;

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
   if(oldVersion<100){
      //your data base need an alter table or something new you added
   }
   if(oldVersion<101){
      //your data base need an alter table or something new you added
   }
}

Upvotes: 1

MikeT
MikeT

Reputation: 57043

You could use :-

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
}

However, also/alternatively simply don't change the Database Version number (4th parameter when constructing the SQLiteOpenHelper subclass i.e. the DatabaseHelper).

both could also be used.

P.S. the onUpgrade method you currently have doesn't delete the database, it drops (deletes) the table within the database.

Upvotes: 2

Related Questions