gpt4 book ai didi

android - 重新打开应用程序时 Room 无法验证数据完整性

转载 作者:行者123 更新时间:2023-12-05 00:13:30 25 4
gpt4 key购买 nike

我正在从 Codelabs 学习如何使用 Room现在我有两张 table

当我从 Android Studio 运行时是正常的

但是当我关闭并重新打开应用程序时出现错误

java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.

重新打开应用程序时出错,而不是在安装时出错

我试图升级版本号,但我仍然遇到错误

这里是我的代码

@Database(entities = [Type::class], version = 3)
abstract class TypeRoomDb : RoomDatabase(){

abstract fun typeDao() : TypeDao

companion object{
@Volatile
private var INSTANCE : TypeRoomDb? = null

fun getDataBase(
context: Context,
scope: CoroutineScope
): TypeRoomDb {
return INSTANCE ?: synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
TypeRoomDb::class.java,
Cons.DB_NAME
)
.fallbackToDestructiveMigration()
.addCallback(TypeDbCallBack(scope))
.build()
INSTANCE = instance

instance
}
}

private class TypeDbCallBack(
private val scope: CoroutineScope
) : RoomDatabase.Callback(){
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
INSTANCE?.let { database ->
scope.launch(Dispatchers.IO) {
populateDb(
database.typeDao()
)
}
}
}
}

fun populateDb(typeDao: TypeDao){
typeDao.deleteAll()
/*out*/
typeDao.insert(
Type(
"000",
"Makan",
0
)
)
typeDao.insert(
Type(
"001",
"Transportasi",
0
)
)
typeDao.insert(
Type(
"002",
"Makanan Ringan",
0
)
)
typeDao.insert(
Type(
"003",
"Komunikasi",
0
)
)

/*in*/
typeDao.insert(Type(
"500",
"Gaji",
1))
typeDao.insert(
Type(
"5001",
"Hadiah",
1
)
)
}

}
}

我的第二张 table

@Database(entities = [LogKeuangan::class], version = 2)
abstract class LogKeuanganRoomDb : RoomDatabase() {
abstract fun logKeuanganDao(): LogKeuanganDao

companion object {
@Volatile
private var INSTANCE: LogKeuanganRoomDb? = null

fun getDataBase(
context: Context,
scope: CoroutineScope
): LogKeuanganRoomDb {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
LogKeuanganRoomDb::class.java,
Cons.DB_NAME
)
.fallbackToDestructiveMigration()
.build()

INSTANCE = instance
instance
}
}

}
}

最佳答案

中清楚提到的一切

java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.

您只需增加版本并将 exportSchema 设置为 false

来自

@Database(entities = [Type::class], version = 3)

@Database(entities = [Type::class], version = 4, exportSchema = false)

注意

@Database creates another db if you want all tables belongs same db then include them into one db. you should not create new db for each table

关于android - 重新打开应用程序时 Room 无法验证数据完整性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62017835/

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