6
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
            }
        }
    }

The above code is the general way of creating singleton of the room database. I wonder why Room.databaseBuilder function requires a context as the parameter. I know this question might be stupid cuz I'm lack understanding of the Context in Android.

  1. What argument should I pass in that parameter?
  2. What can be different if I pass in the Activity context or application?
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
goodonion
  • 1,401
  • 13
  • 25

0 Answers0