Implementing CRUD operations with Room database
Room provides a safer, cleaner way to store structured data in an Android application. Instead of writing raw SQLite queries throughout your project, you define entities, data access objects, and a database class that work together with compile-time checks.
CRUD means create, read, update, and delete. These four operations support common features such as shopping lists, customer records, notes, bookings, and offline product data. Room also works well with Kotlin coroutines, Flow, and ViewModel, making it suitable for beginner projects and production applications.
| Approach | Strengths | Limitations | Best fit |
|---|---|---|---|
| Room | Compile-time query checks, Kotlin support, observable data | Requires setup and architecture | Modern Android apps |
| SQLiteOpenHelper | Direct control over SQLite | More boilerplate and manual migrations | Legacy or highly customised databases |
| SharedPreferences | Simple key-value storage | Not suitable for related records | Settings and small preferences |
| Remote database | Shared, centralised data | Requires network access and backend code | Multi-device and real-time systems |
Why Room suits Android CRUD
Room is an abstraction layer over SQLite. It still stores data locally using SQLite, but separates database responsibilities into clearly defined classes. This makes the code easier to test, maintain, and extend when your app gains more features.
A local database is especially useful when an app must work without a reliable connection. For example, a field-service app used around regional Queensland or Western Australia can save records on the device and synchronise them later. An Android app for Melbourne commuters can also load saved information quickly while the user is underground or moving between stations.
Room uses annotations such as @Entity, @Dao, and @Database. The Room compiler checks SQL statements while building the app, helping you catch incorrect column names and query mistakes before release.
Set up the Android project
Add Room and lifecycle dependencies to your module-level build.gradle.kts file. KSP is commonly preferred for Room code generation in current Kotlin projects.
plugins {
id("com.google.devtools.ksp")
}
dependencies {
implementation("androidx.room:room-runtime:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")
ksp("androidx.room:room-compiler:2.6.1")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.0")
}
The exact versions should match the Android Gradle Plugin and Kotlin version used by your project. Sync Gradle after adding the dependencies, then create a package such as data for the entity, DAO, and database classes.
For a practical example, the application will manage shopping items. A record will contain an ID, item name, quantity, and completion status. The same structure can be adapted for café orders in Sydney, market inventory in Adelaide, or a personal list for an arvo at a local community market.
Define the entity and database
An entity represents a SQLite table. The primary key uniquely identifies each row, and autoGenerate = true allows Room to assign IDs when new items are inserted.
@Entity(tableName = "shopping_items")
data class ShoppingItem(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val name: String,
val quantity: Int,
val purchased: Boolean = false
)
Next, create the Room database class. The version value is important because it must increase when the database schema changes.
@Database(
entities = [ShoppingItem::class],
version = 1,
exportSchema = true
)
abstract class AppDatabase : RoomDatabase() {
abstract fun shoppingItemDao(): ShoppingItemDao
}
Create one database instance rather than constructing a new instance for every screen. In a larger application, dependency injection with Hilt is a strong option. For a smaller tutorial project, a singleton created from the application context is sufficient and prevents unnecessary database connections.
Add CRUD methods to the DAO
The data access object contains the operations used by the rest of the app. Room generates the implementation during compilation, so you only write the interface and SQL needed for custom queries.
@Dao
interface ShoppingItemDao {
@Insert
suspend fun insert(item: ShoppingItem)
@Query("SELECT * FROM shopping_items ORDER BY name ASC")
fun observeAll(): Flow<List<ShoppingItem>>
@Update
suspend fun update(item: ShoppingItem)
@Delete
suspend fun delete(item: ShoppingItem)
}
This DAO covers all CRUD actions. insert() creates a row, observeAll() reads rows, update() changes a matching primary key, and delete() removes the selected record. The Flow return type emits a new list whenever the table changes, so the interface can update without manually refreshing the screen.
For a single record, add a query such as SELECT * FROM shopping_items WHERE id = :itemId. Keep database work out of the main thread by using suspend functions or collecting Flow from a lifecycle-aware coroutine.
Connect the repository and ViewModel
A repository gives the application a consistent place to access the DAO. It can later contain validation, synchronisation, caching, or error handling without filling the ViewModel with database details.
class ShoppingRepository(
private val dao: ShoppingItemDao
) {
val items: Flow<List<ShoppingItem>> = dao.observeAll()
suspend fun add(name: String, quantity: Int) {
if (name.isNotBlank() && quantity > 0) {
dao.insert(
ShoppingItem(
name = name.trim(),
quantity = quantity
)
)
}
}
suspend fun update(item: ShoppingItem) = dao.update(item)
suspend fun remove(item: ShoppingItem) = dao.delete(item)
}
The ViewModel owns screen state and launches database operations in viewModelScope. This prevents a configuration change, such as rotating a phone, from placing database logic inside an Activity.
class ShoppingViewModel(
private val repository: ShoppingRepository
) : ViewModel() {
val items: StateFlow<List<ShoppingItem>> =
repository.items.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5_000),
emptyList()
)
fun addItem(name: String, quantity: Int) {
viewModelScope.launch {
repository.add(name, quantity)
}
}
fun deleteItem(item: ShoppingItem) {
viewModelScope.launch {
repository.remove(item)
}
}
}
A ViewModelProvider.Factory or dependency injection framework is needed to provide the repository constructor. Keeping this wiring explicit at first can make the architecture easier for beginners to understand.
Display and edit stored records
In a Jetpack Compose screen, collect the items state and display it with LazyColumn. A form can call addItem() after validating the name and quantity. Each row can include an edit button and a delete button.
val items by viewModel.items.collectAsStateWithLifecycle()
LazyColumn {
items(items, key = { it.id }) { item ->
ShoppingRow(
item = item,
onDelete = { viewModel.deleteItem(item) },
onToggle = {
viewModel.updateItem(
item.copy(purchased = !item.purchased)
)
}
)
}
}
For XML layouts, the same Flow can be collected from a lifecycle owner and submitted to a RecyclerView ListAdapter. The important principle is the same: the UI observes database state rather than requesting a manual reload after every action.
An edit screen should pass the existing ID back to the ViewModel. Creating a new ShoppingItem with an ID of zero inserts a new row, while copying an existing item preserves its ID and allows @Update to modify the correct row.
Handle validation and database errors
Validation should happen before insertion. Reject blank names, negative quantities, and values that do not make sense for the feature. This protects the database and gives users clear feedback instead of allowing confusing records.
Database operations can still fail because of storage problems, invalid migrations, or unexpected constraints. Wrap important calls in try and catch blocks, expose a success or error state from the ViewModel, and show a useful message in the interface. Avoid displaying raw exception text to users.
Australian apps should also consider privacy from the beginning. If records contain names, addresses, or customer information, review the Australian Privacy Principles and explain local storage and synchronisation in the app’s privacy documentation. Collecting only the data required for the feature reduces risk.
Test migrations and release behaviour
Room requires a migration when the schema changes. For example, adding a category column in version two requires a migration from version one.
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"ALTER TABLE shopping_items ADD COLUMN category TEXT NOT NULL DEFAULT ''"
)
}
}
Register the migration when building the database:
Room.databaseBuilder(
context,
AppDatabase::class.java,
"shopping_database"
)
.addMigrations(MIGRATION_1_2)
.build()
Test insertion, reading, editing, deletion, empty lists, invalid input, and recreation after a configuration change. Instrumented tests can use an in-memory Room database so they do not affect real user data. Test on devices with limited storage and on unreliable mobile connections, conditions that users may encounter outside major Australian cities.
A well-structured Room implementation keeps entities focused on data, DAOs focused on queries, repositories focused on access rules, and ViewModels focused on screen state. That separation gives your Android CRUD feature a reliable foundation for future search, synchronisation, notifications, and reporting.