Step #4: Adding a Database
The third major piece of any Room usage is a @Database. Here, we not only need to add the annotation to a class, but we need to have that class inherit from Room’s own RoomDatabase base class.
Which means… we need another Kotlin class! Again!
Right-click over the com.commonsware.todo.repo package in the java/ directory and choose “New” > “Kotlin File/Class” from the context menu. For the name, fill in ToDoDatabase, and choose “Class” as the kind. Then, Press Enter or Return to create the class, giving you:
package com.commonsware.todo.repo
class ToDoDatabase {
}
Then, replace that implementation with:
package com.commonsware.todo.repo
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
private const val DB_NAME = "stuff.db"
@Database(entities = [ToDoEntity::class], version = 1)
abstract class ToDoDatabase : RoomDatabase() {
abstract fun todoStore(): ToDoEntity.Store
companion object {
fun newInstance(context: Context) =
Room.databaseBuilder(context, ToDoDatabase::class.java, DB_NAME).build()
}
}
The @Database annotation is where we provide metadata about the database that we want Room to manage for us. Specifically:
- We tell it which classes have
@Entityannotations and should have their tables in this database - What is the version code of this database schema — usually, we start at 1, and we increment from there, any time that we add tables, columns, indexes, and so on
The todoStore() method returns an instance of our @Dao-annotated interface. This, coupled with the @Database annotation, tells Room’s annotation processor to code-generate an implementation of our abstract ToDoDatabase class that has an implementation of todoStore() that returns a code-generated implementation of ToDoEntity.Store.
To create the ToDoDatabase instance, in our newInstance() factory function, we use Room.databaseBuilder(), passing it three values:
- a
Contextto use — and since this is a singleton, we need to use theApplicationto avoid any memory leaks - the class representing the
RoomDatabaseto create - a
Stringwith the filename to use for the database
The resulting RoomDatabase.Builder could be further configured, but we do not need that here, so we just have it build() the database and return it.
ToDoDatabase is marked as abstract — the actual class that is used by RoomDatabase.Builder will be a subclass created by Room’s annotation processor.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.