An abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Apache 2.0minSdk 19

Quick Start

Setup Steps

  1. Add the Room dependencies to your build.gradle file.
  2. Define your data entities with @Entity annotations.
  3. Create Data Access Objects (DAOs) with @Dao annotations.
  4. Set up your database class extending RoomDatabase.

Overview

Room is a persistence library for Android that provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite. It simplifies database operations by providing compile-time verification of SQL queries and seamless integration with other Architecture Components.

Features

Compile-time SQL query verification
Reduces boilerplate code
Integration with LiveData and Flow for observable queries
Support for complex relationships and migrations
Type-safe database operations

Use Cases

Storing structured data locally in Android apps
Implementing offline-first application strategies
Managing complex data models with relationships
Caching network data for improved performance

When Not to Use

Simple key-value storage (consider DataStore or SharedPreferences)
Applications requiring real-time sync without local persistence
Scenarios where direct SQLite control is necessary for optimization

Usage Examples

Define an Entity
@Entity
data class User(
    @PrimaryKey val id: Int,
    val name: String
)

A simple User entity with an id and name.

Create a DAO
@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>

    @Insert
    fun insert(user: User)
}

DAO interface with queries and insert operations.

Set up Database
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

Database class defining entities and DAOs.

Common Pitfalls

  • Not planning for database migrations can lead to data loss.
  • Performing database operations on the main thread can cause ANRs.
  • Overusing complex queries without indexing can degrade performance.

Integration

Works well with

ViewModelLiveDataCoroutinesHiltPaging Library
  • Use Room with Coroutines for asynchronous operations, and integrate with ViewModel to manage UI-related data.

Alternatives

SQLite OpenHelper

For lower-level control over SQLite database operations, but with more boilerplate code.

Realm

An object-oriented database alternative with different performance characteristics and licensing.

DataStore

For simpler key-value or typed data storage without the complexity of a full SQL database.

Maintenance & Health

  • Latest version, exact URLs, and SDK numbers are not specified due to uncertainty. Please refer to official Android documentation for up-to-date information.

Related libraries