【问题标题】:Android room database migration is running multiple timesAndroid 房间数据库迁移运行多次
【发布时间】:2019-11-01 05:49:37
【问题描述】:

我正在使用房间数据库创建本地存储,我正在尝试迁移数据库,但在多次调用迁移函数时遇到问题。

我在这里附上我的一段代码。

class DbInstance {
companion object {
    private var db: AppDatabase? = null
    fun getDbInstance(context: Context): AppDatabase {
        if (db == null)
            db = Room.databaseBuilder(
                context,
                AppDatabase::class.java, "mydb"
            )
                .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                .build()
        return db!!
    }

    private val MIGRATION_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {

        }
    }
    private val MIGRATION_2_3 = object : Migration(2, 3) {
        override fun migrate(database: SupportSQLiteDatabase) {
            println("------> called for MIGRATION_2_3")
            database.execSQL(
                "Alter table PaymentDB add column ui_name text"
            )
        }
    }
  }
}



@Database(entities = arrayOf(PaymentDB::class), version = 3)
@TypeConverters(DbTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun paymentDao(): PaymentDao
}

println("------> called for MIGRATION_2_3") 打印了多次(两次)。

【问题讨论】:

  • 嗨,你找到答案了吗?
  • 我终于通过手动检查解决了。
  • 可能与您的问题无关,但您应该在房间数据库中获取应用程序上下文。 Room.databaseBuilder( context.applicationContext, ...

标签: android database kotlin android-room


【解决方案1】:

终于用这个方法解决了。

  if (DbInstance.getDbInstance(context.get()!!).openHelper.readableDatabase.version != Constants.DATABASE_VERSION) {
                        DbInstance.getDbInstance(context = context.get()!!)
                            .openHelper.readableDatabase.needUpgrade(Constants.DATABASE_VERSION)
                        DbInstance.getDbInstance(context = context.get()!!)
                            .openHelper.writableDatabase.needUpgrade(Constants.DATABASE_VERSION)
                    }

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 2019-02-13
    • 2018-11-11
    • 2021-09-02
    • 2021-11-18
    • 2021-06-22
    • 2018-12-01
    • 2020-05-17
    相关资源
    最近更新 更多