Android Room DAO — Complete Guide
In this tutorial, you'll learn about Android Room DAO. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Room DAO queries run on the main thread, return null when you expect data, or throw SQLiteConstraintException on conflicts.
Wrong Approach ❌
@Dao
interface UserDao {
@Query("SELECT * FROM users WHERE id = :id")
fun getUser(id: String): User // Blocking! Crashes on main thread
@Insert
fun insert(user: User) // No conflict handling
@Query("DELETE FROM users WHERE name LIKE :pattern")
fun deleteByName(pattern: String) // SQL injection risk with raw strings
}
Output: IllegalStateException: Cannot access database on the main thread.
Right Approach ✅
@Dao
interface UserDao {
@Query("SELECT * FROM users WHERE id = :id")
suspend fun getUser(id: String): User? // Coroutine-safe
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: User) // Handles duplicate keys
@Query("DELETE FROM users WHERE name LIKE :pattern")
suspend fun deleteByName(pattern: String) // Safe with parameter binding
@Transaction
@Query("SELECT * FROM users")
suspend fun getAllWithOrders(): List<UserWithOrders> // Transactional read
}
Output: Coroutine-safe DAO that runs on background threads with proper conflict handling.
Prevention
- Always use
suspendfunctions for Room operations in Kotlin. - Use
onConflict = OnConflictStrategy.REPLACEorIGNOREfor inserts. - Annotate complex reads with
@Transactionto avoidSQLiteException. - Return
FloworLiveDatafor observable queries.
Common Mistakes with room dao
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro