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:

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:

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.