我试图确保我的数据库始终包含初始行。我通读了如何在首次运行时填充 Android Room 数据库表?我遇到的主要问题是,在创建数据库时,我没有可以使用 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 …Run Code Online (Sandbox Code Playgroud)