Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android app crashes when made some changes in database

Tags:

android

I have developed an android app which consists of database.When i install it on mobile it works fine for first time. when i do some changes in database and install it again without uninstalling the previously installed version, it crashes.

Note:I don't want to uninstall my previous version because i want to retain previously stored data

Any suggestions friends?

like image 841
Govind Avatar asked Nov 05 '12 14:11

Govind


2 Answers

Increase your database version number by 1 when you change database structure. (i.e adding new column, removing existed column, changing datatype of column, changing column name etc...).

And put below two lines inside onUpgrade() method of your db helper class.

db.execSQL("DROP TABLE IF EXISTS your_table_name_goes_here");
onCreate(db);

Everytime it checks the database current version number. If it finds any mismatch between current database version and earlier version then it simply executes onUpgrade() method to upgrade database. So, we drop all our table(s) and create a new table(s) again. So now you can add/remove 'n' number of columns while working with db. What all you have to do is just increase the version number by 1 and execute when you change db structure.

like image 100
Santhosh Avatar answered Oct 24 '22 04:10

Santhosh


When you create a database you will probably use one if these contructors:

public TimePointsSQLiteHelper(Context context, String name,
                           CursorFactory factory, int version) {
    super(context, dbName, factory, dbVersion);
}

private TimePointsSQLiteHelper(Context context) {
    super(context, dbName, null, dbVersion);
}

As you can see, there is a variable dbVersion, this is the one where you indicate the version of the database to avoid the problem you are having. As a suggestion use a final static int variable to old the version/number of your database so you can change it easily. E.g.:

public final static int dbVersion = 1;

Then you should overrite onUpgrade(...) and/or onDowngrade(...) in order to apply the changes to your current app and data.

The simplest and fastest way to do it is the one @SANTHOSH mentioned, just drop all the tables and create them again:

db.execSQL("DROP TABLE IF EXISTS your_table_name");
onCreate(db);

beware that with this solution you will lose your current data saved in your database. You should add more logic to onUpgrade and onDowngrade to migrate the data from one version of the database to the other if you want to keep it.

like image 36
marimaf Avatar answered Oct 24 '22 05:10

marimaf