Add a RoomDatabase Class

Kotlin and Android Development featuring Jetpack — by Michael Fazio (40 / 125)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Add Room to the App | TOC | Create a DAO Class 👉

The PennyDropDatabase is at the core of everything we’re doing with Room. This is where we can define our database tables (via Entity classes), set up versioning, and even include some initialization logic. However, our database interactions won’t be done directly against the PennyDropDatabase but rather via the PennyDropDao class (which we’ll create in a bit).

Create a new class inside the data package called PennyDropDatabase; remember that you can include the package name when creating a class in Android Studio. Once this is created, mark the class as abstract right away and make RoomDatabase its parent class. The last piece is to add the @Database annotation, which tells Room this class is a RoomDatabase and will hold the database configuration. The empty class looks like this:

​ ​package​ ​dev.mfazio.pennydrop.data​

​ ​import​ ​androidx.room.RoomDatabase​

​ @Database(
​ ​// We'll add the Entity classes in a bit.​
​ entities = [],
​ version = 1,
​ exportSchema = ​false​
​ )
​ ​abstract​ ​class​ PennyDropDatabase: RoomDatabase() {
​ ​// Adding this next.​
​ }

The PennyDropDatabase class is going to end up looking a bit odd. We only have a single abstract function called pennyDropDao, which returns an instance of the yet-to-be-created PennyDropDao class, and a…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.