Chapters

Hide chapters

Android Fundamentals by Tutorials

First Edition · Android 14 · Kotlin 1.9 · Android Studio Hedgehog (2023.1.1)

10. Room Database
Written by Kevin D Moore

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

So far, you have a great app to search the internet for recipes. But there are no bookmarks or groceries. When you go to the store, you want to have the list of ingredients needed for those recipes. Do you want to have to search again at the store to get that information?

SQLite

One of the best ways to persist data is with a database. Android provides access to the SQLite database system. This lets you insert, read, update and remove structured data persisted on disk.

In this chapter, you’ll learn about using the Room library.

By the end of the chapter, you’ll know:

  • How to insert, fetch and remove recipes or ingredients.
  • How to use the Repository pattern for a generic way to do these actions.

Room

Room, which Google created in 2018, adds a layer over the built-in SQLite database that Android provides, making it easier to use.

Jug/Var Qpakoywiap Noep/Lmalu Ezkobuaz Sej MIUd nkar Dulumihi Jiam Uplkepuhaig Gofu Xohetubo Piwog SEIj Fibij Ehkigued Boxuq Uzxebeof VSFasu Yelijodo

Room and Android Architecture Components

Room is part of a larger set of libraries known as the Android Architecture Components. The other components are:

App Architecture

Before creating your first Room classes, you must organize the app to achieve a clean architecture. You’ll separate the app into distinct areas of responsibility along these lines:

Mopifomucd Huqe Ojfipw Zerjadxaxha Sufo Quper IE (Xigwuje) SauyKezet

Development Approach

Think about the architecture as a multi-layered cake. Have you ever seen somebody eat a cake one layer at a time? That would be a little odd! Likewise, you won’t build the app one layer at a time. You’ll take one slice at a time. Each slice may cut through all the layers as you slowly build the final product.

UI (Rajzuxu) LoihHidec Nexiwagotw Zila Apdedc Puvxihgidlo (Puay) Hixu Leqim Gle Ubnnunerlala Cipa Uxi zziwe ic e niwo

Adding Room Library

If you’re following along with your app from the previous chapters, open and keep using it with this chapter. If not, locate this chapter’s projects folder and open starter in Android Studio.

Room Classes

Now, you’re ready to add the basic classes required by Room. This includes the Entities, DAOs and the Database. Behind the scenes, Room takes your class structure and creates a SQLite database with tables and column definitions.

Famojuku LupumuPoe OwspiniipjToo QenuxuJosokuko aw:Ujf hilhe: Qftanq odusa: Nbrayl? vuptott: Hjfufq upgbrugnienm:Lqmult? neujnuUxt: Jtyuzc jwofumacaesNijawit: Ibg qealenbYewijan: Uxb soahsEcLekufen: Aps kibzajhw: Ejx Yiyob Owdemeof FigozuTr eh:Igy peqedaUp: Oyr? gehi: Ggteyz eaywo:Qmkijl? ujaso: Txqabt? olobomeg: Bsjufz ozeesn: Huumwi aref: Kwkatq OvmsosieklMn nulosu_velukihi ok xudju ehiqe pijcogk uyfclirheejw xaiqsaApg Hudeni Degca ex pabosaIs beqi iedno afeho imahozad Uydyehaiwv Tuvso Loiz Huaq Baid Zuaf Futidufi Hfaoxeuc Zqopahn

Entities

Recipe Finder requires two entity types to store recipes: RecipeDb and IngredientDb.

RecipeDb

Create a package called database in the data package. Inside this package, create a Kotlin file named RecipeDb.kt and replace the contents with the following:

IngredientDb

Create a Kotlin file named IngredientDb.kt in the data/database package and replace the contents with the following:

DAOs

Next, you’ll define the data access object that reads and writes from the database.

Database

The last piece needed to complete the Room classes is the Database.

Creating the Repository

Your basic Room classes are ready to go. But you’re going to add one more layer of abstraction between Room and the rest of the application code. Doing this makes changing how and where you store the app data easy. This abstraction layer will be provided using a Repository pattern. The repository is a generic store of data that can manage multiple data sources but exposes a unified interface to the rest of the application.

ViewModels

Now that you’ve built the repository, you’ll use it in a ViewModel, a perfect place for it.

Instantiating the Repository

Now that you’ve set up repository usage, it’s time to create it. Like how the Prefs instance is created in the RecipeApp, you’ll create a new RecipeRepository instance. Begin by opening RecipeApp and locating the first // TODO: Add Repository comment. Replace the comment with:

Local Repository Provider

A lot of classes use the repository. How can you provide that repository to all composables in the UI? By using the Local Provider concept. This is a way to provide classes to other composables. You’ll create the class in a higher-level composable and use a Local Provider to provide that instance. Open MainActivity.kt and, after the LocalNavigatorProvider global variable, add:

Bookmarks

It’s time to update the ui/recipes/ShowBookmarks.kt file. Find the // TODO: Provide current item comment and replace the method call below it with:

Recipe Details

The last file to update is ui/RecipeDetails.kt. Find the first // TODO: Add Repository and replace it with:

Updating the ViewModel References

Because you updated the RecipeViewModel to take in a repository, you must fix the instantiation in the GroceryList and RecipeList composable functions. To fix that, open the following files

Updating Previews

The last requirement before building and running the changes is to update the preview composables. Several previews use the RecipeViewModel and require a repository now. In each of the following classes:

Groceries

If you tap the groceries bottom button, you see there are no groceries. To fix that, open ui/groceries/GroceryList.kt. Find // TODO: Get Ingredients and replace it with:

Alternatives

You could use SQLite and the classes that surround it, but it takes a bit of work to create and maintain the database. Here are a few alternatives:

Key Points

  • Room is a great way to create databases and save data.
  • It’s easy to create a database and store recipes.

Where to Go From Here?

In this chapter, you learned how to store data in a database.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now