【发布时间】:2021-04-24 10:47:28
【问题描述】:
我试图确保我的数据库始终包含一个初始行。我通读了How to populate Android Room database table on first run?,我遇到的主要问题是我在创建数据库时使用 Hilt 没有可访问的实例(或者我不知道如何访问它?)。如果我尝试重新使用我编写的provideDatabase Hilt 方法,它会导致 SQLite 数据库泄漏(大概是因为周围没有人使用这些衍生实例来关闭数据库)。这是我的代码:
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
fun provideDatabase(@ApplicationContext context: Context): GameDatabase {
return Room.databaseBuilder(context, GameDatabase::class.java, GameDatabase.GAME_DB_NAME)
.addCallback(
object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
// Initialize the database with the first game
ioThread {
provideDatabase(context).gameDao().createNewGame(Game())
}
}
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
// Ensure there is always one game in the database
// This will capture the case of the app storage
// being cleared
// THIS results in an instance being created that can't be closed - causing DB leaks!
ioThread {
val gameDao = provideDatabase(context).gameDao()
if (gameDao.gameCount() == 0) {
gameDao.createNewGame(Game())
}
}
}
}
).build()
}
@Singleton
@Provides
fun provideGameDao(database: GameDatabase): GameDao {
return database.gameDao()
}
}
那么,我如何获取我的 DAO 来进行初始化?我是否需要在 SQL 中手动制作一个插入语句并在数据库上调用它?
【问题讨论】:
标签: android android-room dagger-hilt