Search code examples
androiddatabasekotlinandroid-room

Handling Room Database update by reacreating from asset except for few columns I need to persist - Android Development


My database has game configuration data and dynamic user data. Every time I update the app, I change the configuration data a lot (records are updated and new records are added), and it easy to just delete the database and recreate from asset. All is updated except the user data which needs to persist and is not impacted by the game configuration update.

So what I would like to do to avoid lengthy migration code:

  1. Read User data from Db (2 columns) store them somewhere temporarily
  2. Delete Entire database and recreate from the asset I updated
  3. Write back the user data into those 2 columns.

From a technical point of view I'm always fidning it difficult to achieve this, and I'm wondering if someone knows if it's possible or has done it before?


Solution

  • If there are just two columns I suggest you to remove it from db and store it somewhere else. For example in SharedPreferences. Or this is not what you can do?

    I am missing details of your implementation.

    If you are using Room, it would be a great opportunity to try out Destructive migrations. When building the db, just enable destructive migrations and the work is done automatically when db version is updated.

    Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
        .createFromAsset("database/myapp.db")
        .fallbackToDestructiveMigration()
        .build()