Sobes.tech
Junior — Middle

How can you perform a database query using Room in Android?

sobes.tech AI

Answer from AI

To access a database using Room in Android, you need to follow several steps:

  1. Define entities — classes that describe the database tables.
  2. Create DAO (Data Access Object) — an interface with methods for data access (insertion, updating, queries).
  3. Create the database — an abstract class inheriting from RoomDatabase, which links entities and DAO.

Example:

@Entity
data class User(
    @PrimaryKey val id: Int,
    val name: String
)

@Dao
interface UserDao {
    @Query("SELECT * FROM User WHERE id = :userId")
    fun getUserById(userId: Int): User

    @Insert
    fun insertUser(user: User)
}

@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

// Usage
val db = Room.databaseBuilder(
    context,
    AppDatabase::class.java, "database-name"
).build()

val userDao = db.userDao()
val user = userDao.getUserById(1)

Thus, through DAO, you can perform queries to the database, and Room automatically generates the necessary code.