使用Android API 32和Room 2.4.2
房间数据库是这样创建的
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
val tempInstance = INSTANCE
if (tempInstance != null)
return tempInstance
synchronized(this) {
val name = "mydb.db"
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
name
).apply {
fallbackToDestructiveMigration()
createFromAsset(name)
}.build()
INSTANCE = instance
return instance
}
}
}
模式版本为1
,预填充的db资产版本为0
。当应用程序第一次启动时,房间db被创建and
,正确地填充了资产数据。但是每当应用程序重新启动时,房间数据库就会被创建并重新填充。如果我将预填充的版本更改为1
,则不会发生重建。
为什么当预填充版本是less
而不是目标版本时,它回退到破坏性和复制数据?
您的问题的答案隐藏在fallbackToDestructiveMigration()
;)
如文档中所述:
Allows Room to destructively recreate database tables if Migrations that would migrate old database schemas to the latest schema version are not found.
When the database version on the device does not match the latest schema version, Room runs necessary Migrations on the database.
If it cannot find the set of Migrations that will bring the database to the current version, it will throw an IllegalStateException.
You can call this method to change this behavior to re-create the database instead of crashing.
Note that this will delete all of the data in the database tables managed by Room.
这样每次更改数据库版本时,都会重新构建数据库。你也可以来回改变你的版本号,所以从1到2,再回到1,如果你喜欢的话。
(总而言之:这可能会防止内存泄漏,一些异常,也可以防止两个具有相同名称和相同扩展名的数据库同时存在)