companion object {
@Volatile
private lateinit var instance: ExampleDatabase
fun getInstance(context: Context): ExampleDatabase {
synchronized(this) {
if(!::instance.isInitialized) {
instance = Room.databaseBuilder(
context.applicationContext, // Why does this require context?
LottoDatabase::class.java,
"lotto_database"
)
.fallbackToDestructiveMigration()
.build()
}
return instance
}
}
}
以上代码是创建房间数据库单例的一般方式。 我想知道为什么 Room.databaseBuilder 函数需要上下文作为参数。我知道这个问题可能很愚蠢,因为我对 Android 中的上下文缺乏了解。
Room.databaseBuilder() 函数用于创建 Room 数据库的实例。出于以下几个原因,它需要上下文作为参数: