Set up Room for type-safe SQLite access with compile-time verification.
Room Database Overview
# Dependencies
implementation("androidx.room:room-runtime:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")
kapt("androidx.room:room-compiler:2.6.1")Entities
@Entity(tableName = "users")
data class UserEntity(
@PrimaryKey val id: String,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "email") val email: String,
@ColumnInfo(name = "avatar_url") val avatarUrl: String?,
@ColumnInfo(name = "created_at") val createdAt: Long,
@ColumnInfo(name = "is_active") val isActive: Boolean = true,
// Ignore in database
@Ignore val fullName: String? = null
)
// Index for faster queries
@Entity(
tableName = "posts",
indices = [Index(value = ["user_id"], name = "idx_posts_user_id")]
)
data class PostEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
@ColumnInfo(name = "user_id") val userId: String,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "content") val content: String,
@ColumnInfo(name = "created_at") val createdAt: Long
)
// Embedded objects
data class Address(
val street: String,
val city: String,
val zipCode: String
)
@Entity(tableName = "profiles")
data class ProfileEntity(
@PrimaryKey val userId: String,
@Embedded val address: Address,
@ColumnInfo(name = "phone") val phone: String?
)
// Type converters for custom types
class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? = value?.let { Date(it) }
@TypeConverter
fun toTimestamp(value: Date?): Long? = value?.time
@TypeConverter
fun fromStringList(value: List<String>?): String? = value?.joinToString(",")
@TypeConverter
fun toStringList(value: String?): List<String> = value?.split(",") ?: emptyList()
}DAOs (Data Access Objects)
@Dao
interface UserDao {
// Insert
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: UserEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(users: List<UserEntity>)
// Update
@Update
suspend fun update(user: UserEntity)
// Delete
@Delete
suspend fun delete(user: UserEntity)
@Query("DELETE FROM users WHERE id = :id")
suspend fun deleteById(id: String)
// Query
@Query("SELECT * FROM users WHERE id = :id")
suspend fun getUser(id: String): UserEntity?
@Query("SELECT * FROM users WHERE is_active = 1 ORDER BY name ASC")
fun getActiveUsers(): Flow<List<UserEntity>>
@Query("SELECT * FROM users WHERE name LIKE :query")
fun searchUsers(query: String): Flow<List<UserEntity>>
@Query("SELECT COUNT(*) FROM users")
suspend fun countUsers(): Int
// Raw query for complex operations
@RawQuery
fun searchUsersRaw(query: String): Flow<List<UserEntity>>
// Transactions
@Transaction
suspend fun insertWithPosts(user: UserEntity, posts: List<PostEntity>) {
insert(user)
postDao.insertAll(posts)
}
}
@Dao
interface PostDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(posts: List<PostEntity>)
@Query("SELECT * FROM posts WHERE user_id = :userId ORDER BY created_at DESC")
fun getPostsByUser(userId: String): Flow<List<PostEntity>>
@Query("DELETE FROM posts WHERE user_id = :userId")
suspend fun deleteByUserId(userId: String)
}Database Class
@Database(
entities = [UserEntity::class, PostEntity::class, ProfileEntity::class],
version = 3,
exportSchema = true
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun postDao(): PostDao
companion object {
@Volatile private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app.db"
)
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.fallbackToDestructiveMigration() // For dev only
.build()
INSTANCE = instance
instance
}
}
}
}
// Migrations
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE users ADD COLUMN last_login INTEGER NOT NULL DEFAULT 0")
}
}
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("""
CREATE TABLE profiles (
user_id TEXT PRIMARY KEY,
street TEXT NOT NULL,
city TEXT NOT NULL,
zip_code TEXT NOT NULL,
phone TEXT,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
)
""".trimIndent())
}
}Repository with Room
class UserRepositoryImpl @Inject constructor(
private val userDao: UserDao,
private val apiService: ApiService
) : UserRepository {
override fun getUsers(): Flow<List<User>> {
return userDao.getActiveUsers()
.map { entities -> entities.map { it.toDomain() } }
.distinctUntilChanged()
}
override suspend fun refreshUsers() {
try {
val response = apiService.getUsers()
val entities = response.map { it.toEntity() }
userDao.insertAll(entities)
} catch (e: Exception) {
// Handle error - maybe emit to error flow
}
}
override suspend fun getUser(id: String): Result<User> {
return try {
val entity = userDao.getUser(id)
if (entity != null) {
Result.success(entity.toDomain())
} else {
val response = apiService.getUser(id)
val entity = response.toEntity()
userDao.insert(entity)
Result.success(entity.toDomain())
}
} catch (e: Exception) {
Result.failure(e)
}
}
}
// Extension for mapping
fun UserEntity.toDomain(): User = User(
id = this.id,
name = this.name,
email = this.email,
avatarUrl = this.avatarUrl,
createdAt = Date(this.createdAt),
isActive = this.isActive
)
fun UserApiResponse.toEntity(): UserEntity = UserEntity(
id = this.id,
name = this.name,
email = this.email,
avatarUrl = this.avatarUrl,
createdAt = this.createdAt.time,
isActive = true
)Testing Room
@RunWith(AndroidJUnit4::class)
class UserDaoTest {
private lateinit var db: AppDatabase
private lateinit var userDao: UserDao
@Before
fun setup() {
db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
AppDatabase::class.java
).allowMainThreadQueries().build()
userDao = db.userDao()
}
@After
fun teardown() {
db.close()
}
@Test
fun insertAndGetUser() = runTest {
val user = UserEntity(
id = "1", name = "John", email = "john@test.com",
avatarUrl = null, createdAt = System.currentTimeMillis()
)
userDao.insert(user)
val retrieved = userDao.getUser("1")
assertNotNull(retrieved)
assertEquals("John", retrieved?.name)
}
@Test
fun getActiveUsersFlow() = runTest {
val user1 = UserEntity("1", "John", "john@test.com", null, 1000, true)
val user2 = UserEntity("2", "Jane", "jane@test.com", null, 2000, false)
userDao.insertAll(listOf(user1, user2))
val activeUsers = userDao.getActiveUsers().first()
assertEquals(1, activeUsers.size)
assertEquals("John", activeUsers[0].name)
}
}Paging with Room
@Dao
interface UserDao {
@Query("SELECT * FROM users WHERE is_active = 1 ORDER BY name ASC")
fun getActiveUsersPaging(): PagingSource<Int, UserEntity>
}
// ViewModel
@HiltViewModel
class UserViewModel @Inject constructor(
private val userRepository: UserRepository
) : ViewModel() {
val users = Pager(
config = PagingConfig(pageSize = 20)
) { userRepository.getUsersPaging() }
.flow
.cachedIn(viewModelScope)
}
// Repository
fun getUsersPaging(): PagingSource<Int, User> {
return userDao.getActiveUsersPaging()
.map { it.toDomain() }
}Database Inspection
# Android Studio → View → Tool Windows → App Inspection → Database Inspector
# View tables, run queries, edit data in real-time
# Or command line:
adb shell
run-as com.example.myapp
sqlite3 databases/app.db
# SQLite commands:
.tables
.schema users
SELECT * FROM users;
.quitTry It
Add Room dependencies. Create entities, DAOs, database class. Add migrations. Test with in-memory database. Use Database Inspector.
# Add to build.gradle.kts:
# implementation("androidx.room:room-runtime:2.6.1")
# implementation("androidx.room:room-ktx:2.6.1")
# kapt("androidx.room:room-compiler:2.6.1")Room mastery
- Create entities with relationships
- Implement DAOs with Flow and suspend functions
- Add TypeConverters for custom types
- Write migrations for schema changes
- Build Repository with Room + Retrofit
- Test DAO with in-memory database
- Implement PagingSource for large lists
- Use Database Inspector to verify data
Room provides compile-time SQL verification. Entities = tables, DAOs = queries. Use Flow for reactive queries. Migrations for schema changes. TypeConverters for custom types. Test with in-memory database. Database Inspector for debugging.