Get a Room

Our NoteDatabase is an abstract class. Somewhere, though, we need to get an instance of it, so we can call notes() and be able to start manipulating the database.

To create a NoteDatabase, you need a RoomDatabase.Builder. There are two functions on the Room class for getting one:

databaseBuilder() will help you create a database backed by a traditional SQLite database file. inMemoryDatabaseBuilder() creates a SQLite database whose contents are only stored in memory — as soon as the database is closed, the memory holding the database contents gets freed.

Both functions take a Context and the Java Class object of your RoomDatabase subclass as parameters. databaseBuilder() also takes the name of the database file to use.

So, we could create a regular, file-backed NoteDatabase via:

private val db =
  Room.databaseBuilder(context, NoteDatabase::class.java, "notes.db").build()

(where context is a suitable Context, such as the Application singleton)

While there are some configuration methods that can be called on the RoomDatabase.Builder, we skip those here, simply calling build() to build the NoteDatabase, assigning it to the db property.

From there, we can:


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.