An abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
Quick Start
Setup Steps
- Add the Room dependencies to your build.gradle file.
- Define your data entities with @Entity annotations.
- Create Data Access Objects (DAOs) with @Dao annotations.
- 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
Use Cases
When Not to Use
Usage Examples
@Entity
data class User(
@PrimaryKey val id: Int,
val name: String
)A simple User entity with an id and name.
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): List<User>
@Insert
fun insert(user: User)
}DAO interface with queries and insert operations.
@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
- 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.