Introduction
Room helps you save and manage app data easily on your phone. It makes working with databases simple and safe.
Room helps you save and manage app data easily on your phone. It makes working with databases simple and safe.
1. Add Room dependencies in build.gradle 2. Create an @Entity data class for your table 3. Create a @Dao interface with database operations 4. Create an abstract @Database class extending RoomDatabase 5. Build the database instance using Room.databaseBuilder()
@Entity
data class User(
@PrimaryKey val id: Int,
val name: String
)@Dao
interface UserDao {
@Insert
suspend fun insert(user: User)
@Query("SELECT * FROM User")
suspend fun getAll(): List<User>
}@Database(entities = [User::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao }
This example shows how to set up Room with a User table, insert a user, and fetch all users.
import android.content.Context import androidx.room.* @Entity data class User( @PrimaryKey val id: Int, val name: String ) @Dao interface UserDao { @Insert suspend fun insert(user: User) @Query("SELECT * FROM User") suspend fun getAll(): List<User> } @Database(entities = [User::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao } // Usage example in a coroutine scope suspend fun demoRoom(context: Context) { val db = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "app-db" ).build() val userDao = db.userDao() userDao.insert(User(1, "Alice")) val users = userDao.getAll() println(users.joinToString()) }
Room simplifies local data storage in Android apps.
Define entities, DAOs, and the database class to set up Room.
Use Room.databaseBuilder() to create the database instance.
@Entity annotation in Room database setup?@Entity annotation marks a Kotlin data class as a table in the Room database.@Dao define data access objects, not tables.@Database and extend RoomDatabase.db.userDao().getAllUsers()?
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAllUsers(): List<User>
}
@Entity
data class User(
@PrimaryKey val id: Int,
val name: String
)
// Assume database is properly created and contains 3 users@Query("SELECT * FROM user") fetches all rows from the user table.val db = Room.databaseBuilder( context, AppDatabase::class.java, "app_db" ).build()
fallbackToDestructiveMigration(), schema changes cause runtime crashes.age to your existing User entity without losing existing data. Which approach correctly updates the Room database?Pass the test and this pattern moves unknown