gpt4 book ai didi

Android 房间数据库迁移运行多次

转载 作者:行者123 更新时间:2023-11-30 04:58:42 24 4
gpt4 key购买 nike

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

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

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") 打印了多次(两次)。

最佳答案

最后用这个方法得到了解决方案。

  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)
}

关于Android 房间数据库迁移运行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58654659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com