Discuss the implementation and use of Room Persistence Library in Android.

Instruction: Explain how you would design and implement a database using Room. Include examples of how to define entities, DAOs (Data Access Objects), and the database itself. Also, discuss how you would handle migrations for schema changes.

Context: This question assesses the candidate's familiarity with the Room Persistence Library as part of Android Jetpack, their understanding of SQLite database abstraction, and their ability to implement a robust local storage solution. It probes into the candidate's skills in handling data persistence, designing database schemas, and managing data migrations, which are critical for maintaining app data integrity and user experience.

Updated

Official answer

Room provides typed entities and DAOs over SQLite, with generated query/schema checks. I would first define the keys, nullable fields and transaction boundaries, then keep database operations out of UI code.

Here is a Room 2.8.5 Android example using its SupportSQLite migration path. It assumes an Android Kotlin project with minSdk 23 or higher, matching room-runtime/room-compiler dependencies, KSP configured, and a schema export directory. Version 1 had id, title and author; version 2 adds nullable publishedYear. No SQLiteDriver is configured in this example.

import android.content.Context
import androidx.room.Database
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

@Entity(tableName = "books")
data class Book(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    val author: String,
    val publishedYear: Int? = null
)

@Dao
interface BookDao {
    @Query("SELECT * FROM books ORDER BY id")
    suspend fun getAllBooks(): List<Book>

    @Insert(onConflict = OnConflictStrategy.ABORT)
    suspend fun insertBook(book: Book): Long
}

@Database(entities = [Book::class], version = 2, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
    abstract fun bookDao(): BookDao
}

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE books ADD COLUMN publishedYear INTEGER")
    }
}

fun createDatabase(context: Context): AppDatabase =
    Room.databaseBuilder(
        context.applicationContext, AppDatabase::class.java, "books.db"
    ).addMigrations(MIGRATION_1_2).build()

Create and retain one database instance per process through the application's dependency owner; do not call this factory on every query. Call the suspend DAO from an appropriate coroutine. Inserting Book(title = "A", author = "B") returns a generated ID; duplicate explicit IDs fail rather than silently replacing an existing row. Updates should have a deliberate conflict policy.

Commit exported schemas and use MigrationTestHelper on the supported upgrade paths, including existing records and fresh installs. The added field should be null for old rows while IDs/titles/authors remain unchanged. Verify the resulting schema as well as data. Destructive fallback is acceptable only when losing that database's contents is an explicit product decision. SQLite migration checks alone do not replace Room-generated-code and device tests.

Room 2.8 release and dependencies, Room entities and DAOs, Room migration testing

Related Questions