Migrate data from one version to another - Android Sqlite

Asked

Viewed 225 times

3

In the application I am working on, I have to save the data from a specific table when the application is updated. This action needs to happen before the table is discarded in the onUpgrade method. I need to do this because when the application is updated I want the user to continue logging into the system after the update. User data is the only data I want to reuse. my onUpgrade method is like this:

public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {

    TableUtils.dropTable(connectionSource, User.class, true);
    ... other tables


    // after we drop the old databases, we create the new ones
    onCreate(db, connectionSource);

} catch (SQLException e) {
    Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
    throw new RuntimeException(e);
}
}

How can I implement this persistence?

2 answers

4


I don’t know what kind of upgrade you want to do to the database but this upgrade can be done with or without the need to delete and then recreate all tables.
For this, in the method onUpdate(), use SQL commands of type ALTER TABLE and CREATE TABLE to make the changes.

If this is not feasible/practical or just want to keep some data, read this data to memory, do the drop of the tables, call the method onCreate() and restore saved data.

  • Okay, @ramaral I will try to implement in this bring to memory option.

  • Solved! I saw here with the project manager and there was no effective need to delete the user table. I load the user into memory, no longer delete the table in onUpgrade and when I call onCreate again do not create again if the user table is already created.

1

One option would be to not save the user data in the database but in sharedPreferences, that do not work with upgrade.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.