Challenge - 5 Problems
Room Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What is the output of this Room query?
Given this DAO function, what will be the result of calling
getAllUsers() if the database has 3 users?Android Kotlin
import androidx.room.* @Entity data class User( @PrimaryKey val id: Int, val name: String ) @Dao interface UserDao { @Query("SELECT * FROM User") fun getAllUsers(): List<User> }
Attempts:
2 left
💡 Hint
The query selects all rows from the User table.
✗ Incorrect
The @Query annotation with 'SELECT * FROM User' returns all rows as a list of User objects.
📝 Syntax
intermediate2:00remaining
Which option correctly inserts a User into the database?
Select the correct DAO function to insert a User object into the Room database.
Android Kotlin
import androidx.room.* @Entity data class User( @PrimaryKey val id: Int, val name: String ) @Dao interface UserDao { // Insert function here }
Attempts:
2 left
💡 Hint
Use the Room annotation designed for inserting entities.
✗ Incorrect
The @Insert annotation tells Room to generate code to insert the entity. Option B is invalid SQL syntax, C is not Room syntax, and D uses @Update which is for updating, not inserting.
❓ lifecycle
advanced2:00remaining
What happens if you update a User with a non-existing ID?
Consider this DAO update function. What will happen if you call it with a User object whose ID does not exist in the database?
Android Kotlin
@Update fun updateUser(user: User): Int
Attempts:
2 left
💡 Hint
Think about how Room handles updates when no matching row exists.
✗ Incorrect
Room's @Update returns the number of rows updated. If no row matches the primary key, it returns 0 and does not insert a new row.
🔧 Debug
advanced2:00remaining
Why does this delete query cause a runtime error?
This DAO delete function causes a runtime crash. What is the cause?
Android Kotlin
@Query("DELETE FROM User WHERE id = :userId")
fun deleteUser(userId: Int)Attempts:
2 left
💡 Hint
Check the data type of the primary key in the User entity.
✗ Incorrect
If the User entity's id is Int, passing a String parameter causes a type mismatch at runtime.
🧠 Conceptual
expert3:00remaining
How does Room handle conflicts on insert with @Insert(onConflict = OnConflictStrategy.REPLACE)?
If you insert a User with an existing primary key using
@Insert(onConflict = OnConflictStrategy.REPLACE), what happens?Attempts:
2 left
💡 Hint
Consider what REPLACE means in SQLite conflict strategies.
✗ Incorrect
REPLACE deletes the existing row with the same primary key and inserts the new row, effectively replacing it.