1 Get instance of the database class
Marcel van der Heide edited this page 2023-01-13 17:04:33 +01:00

Get instance of the database class

To get an instance of your database class, we simply use the standard databaseBuilder method of Room.

fun databaseBuilder (context: Context, klass: Class<T>, name: String)

Or the inMemoryDatabaseBuilder:

fun inMemoryDatabaseBuilder(context: Context, klass: Class<T>)

Notice that we are required to pass a Java Class as second argument. This has to be the class of our RoomExDatabase, which can be retrieved with the static getDbClass method in RoomExDbBase class.

fun getDbClass(): Class<out RoomDatabase>

Example

@Singleton
fun getAppDatabase(appContext: Context): RoomExDbBase {
        return Room.databaseBuilder(
            appContext,
            RoomExDbBase.getDbClass(),
            "roomex_sample_db"
        ).build() as RoomExDbBase
    }

Note: When using a custom database class, be sure to cast it correctly.