Y
Y
Yaroslav Pronin2020-01-06 19:51:26
Android
Yaroslav Pronin, 2020-01-06 19:51:26

Android Room: how to know that a migration has happened?

I am migrating an old project to Android Jetpack, including migrating the old database to Room. I ran into the following problem: in the old data storage scheme, some of the information was in the database, and the other part was in the file system in the Android / data folder. It was decided to transfer this part to the new Room schema using the Migration mechanism and copy the data from the files to the database. But the problem arises - I cannot get the Context from the Migration, which is necessary to access the data directory using getExternalFilesDir, and I also cannot find out that the Migration has been completed and that the migration has taken place at all, since there is no onUpgrade callback. Room allows you to set a callback in three cases - onOpen, onCreate and onDestructiveMigration, but none of them fit. onCreate is only called when the database is first created and is not called after migrating to a new schema. What is the correct way in this case? How can I know that a migration has taken place and take additional steps?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AndroidDev2015, 2020-01-07
@AndroidDev2015

Something like this:

fun databaseBuilder(context: Context): MyAppDatabase {
            return Room.databaseBuilder(
                context.applicationContext,
                MyAppDatabase::class.java,
                "MyApp.db"
            ).addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    // create code...
                }
            }).addMigrations(
                object : Migration(1, 2) {
                    override fun migrate(database: SupportSQLiteDatabase) {
                        insertFromCVS(context, database) // доступен context
                    }
                }).build()

https://developer.android.com/training/data-store...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question