madprops
madprops

Reputation: 4023

Prevent data loss from sqlite database onUpgrade

Right now my onUpgrade method looks like this:

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

This currently makes a new table everytime my app is updated from the market.

How can I prevent my table from being deleted and only being recreated or modified when I wanted to?

Upvotes: 0

Views: 418

Answers (3)

Jonas
Jonas

Reputation: 1

See this solution (in Portuguese):

Just create temporary tables with all data(backup), drop/create others database tables and copy(re-insert) temporary table data to new structure. A solution that works, but probably not in every case.

Upvotes: 0

Taras Leskiv
Taras Leskiv

Reputation: 1875

You should check database versions. onUpgrade() is executed only if current version is older than the new one. Check if your subclass's of SQLiteOpenHelper constructor every time passes the same parameter (last one). In you case the database will not be recreated if your database version remains the same, onUpgrade() will not be executed.

public DBHelper(Context context) {
      super(context, DB_NAME, null, DB_VERSION);
}

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006819

How can I prevent my table from being deleted and only being recreated or modified when I wanted to?

Delete the current body of your onUpgrade() method and do a more sophisticated upgrade process: adding tables, dropping tables, altering tables, etc.

Upvotes: 1

Related Questions