Android Room 在迁移后用新数据填充数据库?

Android Room populate database with new data after migration?

我已经在 Play 商店中发布了一个应用程序,它在 onCreate 回调中使用数据预填充 Room 数据库。从 JSON 文件中读取数据并将其放入数据库中。从 JSON 文件再次将数据导入数据库(将新记录添加到 table)一切正常。

这是我的 RoomDatabase create 方法:

private fun create(context: Context): MyDatabase {
        val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE dogs ADD COLUMN language TEXT")
            }
        }
        return Room.databaseBuilder(
            context.applicationContext,
            MyDatabase::class.java,
            DB_NAME
        )
            .addMigrations(MIGRATION_1_2)
            // prepopulate the database after onCreate was called
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    GlobalScope.launch {
                        getInstance(context)?.let { DatabaseUtils.prepopulateDatabase(context, it) }
                    }
                }
            })
            .build()
    }

有没有无需手动编写数百 SQL 请求的简单方法? 或者,如果有一种方法可以删除整个数据库并使用全新数据创建一个新数据库,也许对我来说也是一个选择。

在此先感谢大家 ;)

您可以使用 fallbackToDestructiveMigration drop/clear 以前的数据库。

database = Room.databaseBuilder(context.getApplicationContext(),
                    UsersDatabase.class, "Sample.db")
            .fallbackToDestructiveMigration()
            .build();

参考这篇 google 文章中的场景 3 Understanding migrations with Room

也许这是最简单的方法:

private const val IS_DB_RECREATED = "is_database_recreated"

class App : Application(), HasActivityInjector {

    override fun onCreate() {
        super.onCreate()
        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        val isDBRecreated = sharedPreferences.getBoolean(IS_DB_RECREATED, false)

        if (!isDBRecreated) {
            deleteDatabase(MyDatabase.DB_NAME)
            sharedPreferences.edit().putBoolean(IS_DB_RECREATED, true).apply()
        }
    }
}

数据库中的所有数据都会丢失,但是当第一次访问新数据库时,它将是pre-populated,我也可以更改方案。