In my main Activity? How would I access it from other Activities / Fragments?
Found this code example (at the bottom of the page):
@Database(entities = [SleepNight::class], version = 1, exportSchema = false)
abstract class SleepDatabase : RoomDatabase() {
abstract val sleepDatabaseDao: SleepDatabaseDao
companion object {
@Volatile
private var INSTANCE: SleepDatabase? = null
fun getInstance(context: Context): SleepDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
SleepDatabase::class.java,
"sleep_history_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
}
return instance
}
}
}
}
However, I'm having a few issues with it:
Why are there two instance/INSTANCE variables? I think one should suffice.
The INSTANCE variable is nullable. I think the kotlin way would be a
lateinitvariable.syncronized(this): What isthisactually in a companian object? Will it be the RoomDatabase instance? Or the caller? That would break the synchronization intent.The Dao access is a variable. The tutorial shows them as functions. Is it valid to access the Dao with a variable instead of a function?
Is it a good idea to store the Room DB variable in a companion object?
On the one hand this code snippet provides a convenient solution to my introductory question. On the other hand, since I'm having so many issues with this code, I'm not sure if this is really a good idea.
Is there a generally accepted way where to put the Room DB variable? Is above code a good guide? Or should I rather follow a different approach?