Complete the code to define a Room entity with a primary key.
import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class User( @PrimaryKey val [1]: Int, val name: String )
The primary key field is commonly named id to uniquely identify each entity.
Complete the code to create a DAO interface with a query to get all users.
import androidx.room.Dao import androidx.room.Query @Dao interface UserDao { @Query("SELECT * FROM user") fun [1](): List<User> }
The method name getAllUsers clearly describes the action of fetching all user records.
Fix the error in the Room database abstract class declaration.
import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [User::class], version = 1) abstract class AppDatabase : [1]() { abstract fun userDao(): UserDao }
The Room database class must extend RoomDatabase to work properly.
Fill both blanks to build the Room database instance in a singleton pattern.
import android.content.Context import androidx.room.Room object DatabaseBuilder { private var INSTANCE: AppDatabase? = null fun getInstance(context: Context): AppDatabase { if (INSTANCE == null) { INSTANCE = Room.[1](context.applicationContext, AppDatabase::class.java, "app_db").[2]() } return INSTANCE!! } }
The method databaseBuilder starts building the database, and build() finalizes the creation.
Fill all three blanks to define an entity with an auto-generated primary key and a non-null column.
import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.ColumnInfo @Entity data class Product( @PrimaryKey(autoGenerate = [1]) val id: Int = 0, @ColumnInfo(name = "product_name") val [2]: String, val price: Double = [3] )
Setting autoGenerate = true enables automatic ID generation. The product name field is named name. The price defaults to 0.0.