【发布时间】:2021-05-03 11:56:24
【问题描述】:
我希望我的用户能够将房间数据库保存在谷歌驱动器上,然后从它加载到另一台设备上,第一部分已经实现,但我正在努力用新文件填充房间数据库。
这是我的单例数据库:
companion object {
@Volatile
private var INSTANCE: AppRoomDataBase? = null
fun getDatabase(context: Context): AppRoomDataBase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppRoomDataBase::class.java,
"product_database"
).build()
INSTANCE = instance
return instance
}
}
}
然后当用户想从谷歌驱动器加载数据库时:
private fun loadFileFromDrive() {
val file = File(getExternalFilesDir(null), "product_database")
mDriveServiceHelper.queryFiles().addOnSuccessListener { fileList ->
val database = fileList.files.first()
mDriveServiceHelper.downloadFile(file,database.id)?.addOnSuccessListener {
prepopulateRoomDatabaseWithFile(file)
}
}
}
private fun prepopulateRoomDatabaseWithFile(file : File){
Room.databaseBuilder(application,AppRoomDataBase::class.java,"product_database")
.createFromFile(file)
.build()
}
但这不起作用,只有关于如何最初从文件创建数据库的文档,但我找不到任何关于如何仅在需要时用新的 Room 数据库覆盖当前 Room 数据库的信息,这可能吗?
【问题讨论】:
标签: android kotlin android-room