5.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 GroceryDatabase
class to hold the database. GroceryDatabase
defines 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 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.
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:
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:
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!
Last updated