0
0
Android Kotlinmobile~7 mins

Room queries (Insert, Update, Delete, Select) in Android Kotlin

Choose your learning style9 modes available
Introduction

Room queries let your app save, change, remove, and get data from a database easily. This helps your app remember things even after closing.

Saving user notes or messages in an app
Updating user profile information like name or email
Deleting old or unwanted data like completed tasks
Fetching a list of saved items to show on screen
Syntax
Android Kotlin
/* Insert */
@Insert
fun insertItem(item: Item)

/* Update */
@Update
fun updateItem(item: Item)

/* Delete */
@Delete
fun deleteItem(item: Item)

/* Select */
@Query("SELECT * FROM item_table")
fun getAllItems(): List<Item>
Use @Insert to add new data to the database.
Use @Update to change existing data, matching by primary key.
Use @Delete to remove data by matching the object.
Use @Query with SQL to get data; you can write any SELECT statement.
Examples
Adds a new user to the database.
Android Kotlin
@Insert
fun addUser(user: User)
Updates user details already saved.
Android Kotlin
@Update
fun updateUser(user: User)
Removes the user from the database.
Android Kotlin
@Delete
fun deleteUser(user: User)
Gets all users older than 18.
Android Kotlin
@Query("SELECT * FROM user_table WHERE age > 18")
fun getAdultUsers(): List<User>
Sample App

This example shows how to insert, update, delete, and select users in a Room database using Kotlin. The User data class defines the table. UserDao interface has methods with Room annotations to perform database actions.

Android Kotlin
import androidx.room.*

@Entity(tableName = "user_table")
data class User(
  @PrimaryKey val id: Int,
  val name: String,
  val age: Int
)

@Dao
interface UserDao {
  @Insert
  fun insertUser(user: User)

  @Update
  fun updateUser(user: User)

  @Delete
  fun deleteUser(user: User)

  @Query("SELECT * FROM user_table")
  fun getAllUsers(): List<User>
}

// Usage example (not full app):
fun main() {
  val userDao: UserDao = TODO("Get UserDao from Room database")

  val user = User(1, "Alice", 25)
  userDao.insertUser(user) // Save user

  val users = userDao.getAllUsers() // Get all users
  println(users)

  val updatedUser = user.copy(age = 26)
  userDao.updateUser(updatedUser) // Update age

  userDao.deleteUser(updatedUser) // Remove user
}
OutputSuccess
Important Notes

Room database operations should be run on a background thread to keep the app smooth.

Always use suspend functions or RxJava for queries in real apps to avoid blocking the main thread.

Primary key is important to identify which row to update or delete.

Summary

Use @Insert, @Update, @Delete annotations for basic data changes.

Use @Query with SQL to read data from the database.

Room helps keep your data safe and easy to manage inside your app.