6 Retrieving a Dao
Marcel van der Heide edited this page 2023-01-16 13:26:03 +01:00

Retrieving a Dao

To get an instance of a Dao in Android Room, you would normally use the RoomDatabase class to retrieve an instance. This has been slightly altered, since the RoomDatabase aswell as the actuall Dao classes will be generated by RoomEx.

Custom database class

RoomEx allows the creation of custom, abstract database class. Such a class should be marked with the @RoomExDb annotation and should implement the RoomExDbBase class.
Using this pattern, you should notice that you gain access to the RoomDatabase, aswell as to the RoomExDbBase methods. One of these methods is the fetchDaoForEntity method.

fun <T : RoomExEntity> fetchDaoForEntity(entityKClass: KClass<T>): RoomExDao<T>

Since RoomEx uses a single Dao for each entity, we can simply pass the entity to get the desired Dao. Internally, the corresponding RoomDatabase method to retrieve that Dao will invoked.

Ofcourse, since your Database class has to be abstract, you still need to get an instance of your database class. This part is no different than when using Room, only that you are using a different database class. The chapter "Get instance of the database class" describes how to get instance of your custom database class.

The fetchDaoForEntity method returns a RoomExDao<T> which you can simply cast to your custom Dao class, or to the RoomExAutoDao<T> for automatically generated Dao classes.

Auto generated database class

When no custom class has been created, RoomEx will auto create a database class for us. Just like with the custom database class, and with standard Room, we are still required to get an actuall instance of the database class. The chapter "Get instance of the database class" describes how to get instance of the automatically generated database class.