Why Room.databaseBuilder function requires context as the parameter in a Room database?
Asked Answered
F

1

7
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?
Fullblooded answered 11/3, 2020 at 8:20 Comment(0)
L
0

The Room.databaseBuilder() function in Android is used to create an instance of the Room database. It requires a context as a parameter for a few reasons:

  1. To create a database instance. Room uses the context to create a database instance in the application's database directory.
  2. To access the database file. Room uses the context to access the database file, which is stored in the application's internal storage.
  3. To provide access to the database to other components. Room uses the context to provide access to the database to other components of the application, such as the DAO and ViewModel classes.
Laager answered 6/11, 2023 at 7:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.