9.6 Databases

Creating the Database

The database does the heavy lifting of storing and retrieving your entities through the abstract functions of your DAO.
The following code defines an GroceryDatabaseclass to hold the database. GroceryDatabasedefines the database configuration and serves as the app's main access point to the persisted data. The database class must satisfy the following conditions:
  • The class must be annotated with a @Database annotation that includes an entities array that lists all of the data entities associated with the database.
  • The class must be an abstract class that extends RoomDatabase.
  • For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.
@Database(entities = [GroceryItem::class], version = 1)
abstract class GroceryDatabase: RoomDatabase() {
abstract fun groceryItemDao(): GroceryItemDao

Accessing the Database

After you have defined the data entity, the DAO, and the database object, you can use the following code to create an instance of the database:
val db = Room.databaseBuilder(
GroceryDatabase::class.java, "grocery-database"
If you are using your database across your app, you should only need one instance of the Room Database class. Having the number of instances of a Database can lead to memory leaks. Therefore one should use the singleton patterns in the Database to keep one unified instance!
From there, you can call any of the methods defined in your DAO:
val groceryItemDao = db.groceryItemDao()
val groceryItems = groceryItemDao.getAll()
Note: since database access can take a long time, we want to run it in the background--otherwise the UI thread can be blocked, causing the app to freeze or just be generally slow. The Rooms library can be combined with Coroutines to help mitigate this issue!