简体   繁体   中英

Android SQLite - new database with another app version

I have an app, where I use SQLite database, provided by me, so it is fixed and the user will not update anything in the database. Only results will be shown from that database.

The problem is - I am creating that database programatically ONLY on first run of the app:

  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    if(!prefs.getBoolean("firstTime", false)) {
        final DatabaseHelper myDb;
        myDb = new DatabaseHelper(this);
        myDb.deltab();
        myDb.insertData("Josh","Smith","012345678","something","something","something");myDb.insertData("Josh","Smith","012345678","something","something","something"); }

    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("firstTime",true);
    editor.apply();

First I drop the table (just to be sure it will create it from start) and then I create it and insert the data.

This is working fine on first app run.

But if I need to add some more data into that table in the future, or change any existing data in the next app version, how can I do that?

If the user downloads the new version of the app, the firstTime condition is not going to run, because he already started the old app before and by upgrading the version the sharedpreferences are not reset.

Looks like you're already using SQLiteOpenHelper to manage your databases (guessing on DatabaseHelper ). That makes things easier. You can use it to support your needs.

  • Lose the SharedPreferences first run check as unnecessary. Just set up your database in your helper onCreate() . It gets run once if the database file did not exist in the device ie "first run".

  • To update from an old version to a new one, bump up the database version you're supplying to SQLiteOpenHelper constructor and do your data changes in onUpgrade() . It gets run if there was a database file with an older version number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM