Get a Room
In this example, the database is a singleton. TripDatabase has a static getter method, cunningly named get(), that creates our singleton. get(), in turn, calls a create() method that is responsible for creating our TripDatabase:
static TripDatabase create(Context ctxt, boolean memoryOnly) {
RoomDatabase.Builder<TripDatabase> b;
if (memoryOnly) {
b=Room.inMemoryDatabaseBuilder(ctxt.getApplicationContext(),
TripDatabase.class);
}
else {
b=Room.databaseBuilder(ctxt.getApplicationContext(), TripDatabase.class,
DB_NAME);
}
return(b.build());
}
To create a TripDatabase, we use a RoomDatabase.Builder, which we get by calling one of two methods on the Room class:
-
databaseBuilder()is what you will normally use -
inMemoryDatabaseBuilder()does what the method name suggests: it creates an in-memory SQLite database, useful for instrumentation tests where you do not necessarily need to persist the data for a user
Both of those methods take a Context and the Java Class object for the desired RoomDatabase subclass. databaseBuilder() also takes the filename of the SQLite database to use, much as SQLiteOpenHelper does in traditional Android SQLite development.
While there are some configuration methods that can be called on the RoomDatabase.Builder, we skip those here, simply calling build() to build the TripDatabase. The result is that when we call get(), we get a singleton lazy-initialized TripDatabase.
From there, we can:
- Call
tripStore()on theTripDatabaseto retrieve theTripStoreDAO - Call methods on the
TripStoreto query, insert, update, or deleteTripobjects
We will see how to do that in the next chapter, where we look at how to write instrumentation tests for our Room-generated database code.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.