Android room数据库迁移正在运行多次
我正在使用room数据库创建本地存储,我正在尝试迁移数据库,但在多次调用迁移函数时遇到了问题 我在这里附上我的代码Android room数据库迁移正在运行多次,android,database,kotlin,android-room,Android,Database,Kotlin,Android Room,我正在使用room数据库创建本地存储,我正在尝试迁移数据库,但在多次调用迁移函数时遇到了问题 我在这里附上我的代码 class DbInstance { companion object { private var db: AppDatabase? = null fun getDbInstance(context: Context): AppDatabase { if (db == null) db = Room.databaseBuild
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(“-->调用了迁移”\u 2\u 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)
}
最后利用这种方法得到了解决方案
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)
}
嗨,你找到答案了吗?我最终通过手动检查解决了问题。嗨,你找到答案了吗?我最终通过手动检查解决了问题。