Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to make a migration script for a specific version

My app's currently released versionCode is 15, & I want to run some migration code to fix users' data on the app's database (not the schema structure).

So, how to run the fixing code only once for people upgrading from any version less than or equal 15 to any version higher than or equal 16 ?

like image 624
AbdelHady Avatar asked Mar 02 '26 21:03

AbdelHady


1 Answers

If you are talking about migratin a sql database, then SQLiteOpenHelper.onUpgrade() is the right place to put your migration code into. In this case you don't have to rely on the versionCode, but rather on the database version number. So just increment the database version number in your next app update and SQLiteOpenHelper will automatically call onUpgrade(). You can do queries and table definition so. you may query the whole data, load it in memory, manipulate this data in memory, change the sql table definition, clear the table and reinsert the (manipulated / migrated) data into your sql tables.

If you are talking about migrating other data (like Shared preferences, files on external storage etc.) then you may subclass Application an override onCreate(). Then you check if versionCode == 16 and do your migration stuff and afterwards you have to store the information that the migration has been done successful (to not rerun migration again on next app start). I would to that by saving a boolean flag into shared preferences.

like image 69
sockeqwe Avatar answered Mar 05 '26 10:03

sockeqwe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!