Table of Contents

Persist Data with Room

https://developer.android.com/codelabs/basic-android-kotlin-compose-persisting-data-room

Gitlab repo: https://github.com/google-developer-training/basic-android-kotlin-compose-training-inventory-app/tree/main

1. Before you begin

Room is a persistence library that's part of Android Jetpack. Room is an abstraction layer on top of a SQLite database. SQLite uses a specialized language (SQL) to perform database operations. Instead of using SQLite directly, Room simplifies the chores of database setup, configuration, and interactions with the app. Room also provides compile-time checks of SQLite statements.

…

2. App overview

…

3. Starter app overview

You can browse the code in the Inventory app GitHub repository.

4. Main components of Room

5. Create an item Entity

6. Create the item DAO

7. Create a Database instance

“Template code” for future projects:

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
 
/**
* Database class with a singleton Instance object.
*/
@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class InventoryDatabase : RoomDatabase() {
 
    abstract fun itemDao(): ItemDao
 
    companion object {
        @Volatile
        private var Instance: InventoryDatabase? = null
 
        fun getDatabase(context: Context): InventoryDatabase {
            // if the Instance is not null, return it, otherwise create a new database instance.
            return Instance ?: synchronized(this) {
                Room.databaseBuilder(context, InventoryDatabase::class.java, "item_database")
                    .build()
                    .also { Instance = it }
            }
        }
    }
}

8. Implement the Repository

…

9. Add the save functionality

…

View the database content using Database Inspector

Get the solution code

Summary

Learn more