5.6 Databases
Last updated
Was this helpful?
Last updated
Was this helpful?
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 annotated with a annotation that includes an array that lists all of the data entities associated with the database.
The class must be an abstract class that extends .
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.
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 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 to help mitigate this issue!