Storing Data in a Room

There are three main options for storing data locally in an Android device:

In this chapter, we will look at the second of those: SQLite databases. SQLite is an embedded relational database, so you can use standard SQL, while the database is a simple set of files on the device, not some server.

The Jetpack solution for working with SQLite databases is called Room. Google describes Room as providing “an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.”

In other words, Room aims to make your use of SQLite easier, through a lightweight annotation-based implementation of an object-relational mapping (ORM) engine.

This chapter only scratches the surface of what Room has to offer, though it does include a section on other Room features. Room is a fairly powerful library, and with that power comes a fair bit of complexity, once you get past the basics.

The Bookmarker sample module in the Sampler and SamplerJ projects is an app that tracks bookmarks. You will be able to share Web pages from your favorite Web browser (if it offers a “Share” option), and Bookmarker will save that URL in a Room database. It will also present the list of saved bookmarks to you, sorted by page title, and you can click on an entry in the list to view that Web page in your favorite browser.

Room Requirements

To use Room, you need two dependencies in your module’s build.gradle file:

  1. The runtime library version, using the standard implementation directive
  2. An annotation processor, using the annotationProcessor directive (in Java) or the kapt directive (in Kotlin)

The Java edition of Bookmarker pulls in both of those:

  implementation "androidx.room:room-runtime:2.3.0"
  annotationProcessor "androidx.room:room-compiler:2.3.0"

The Kotlin edition pulls in both of those, along with an additional dependency:

  implementation "androidx.room:room-runtime:2.3.0"
  implementation "androidx.room:room-ktx:2.3.0"
  kapt "androidx.room:room-compiler:2.3.0"

androidx.room:room-runtime is the runtime library, while androidx.room:room-compiler is the annotation processor. The third dependency in the Kotlin edition is androidx.room:room-ktx, which gives Room the ability to work with Kotlin coroutines for threading purposes.

The Kotlin edition also uses Koin for dependency inversion:

  implementation "io.insert-koin:koin-androidx-viewmodel:2.2.3"

Prev Table of Contents Next

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