0
0
Android Kotlinmobile~5 mins

Room database setup in Android Kotlin

Choose your learning style9 modes available
Introduction

Room helps you save and manage app data easily on your phone. It makes working with databases simple and safe.

You want to save user notes or settings locally on the device.
You need to keep a list of items like tasks or contacts that stay after the app closes.
You want to store data offline and sync later when internet is available.
Syntax
Android Kotlin
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()
Use @Entity to define a table in the database.
Use @Dao to define methods for inserting, querying, updating, and deleting.
Examples
Defines a User table with id as the primary key and a name column.
Android Kotlin
@Entity
data class User(
  @PrimaryKey val id: Int,
  val name: String
)
Defines methods to add a user and get all users from the User table.
Android Kotlin
@Dao
interface UserDao {
  @Insert
  suspend fun insert(user: User)

  @Query("SELECT * FROM User")
  suspend fun getAll(): List<User>
}
Creates the Room database class linking the User entity and UserDao.
Android Kotlin
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
  abstract fun userDao(): UserDao
}
Sample App

This example shows how to set up Room with a User table, insert a user, and fetch all users.

Android Kotlin
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())
}
OutputSuccess
Important Notes
Always run database operations off the main thread to avoid freezing the app UI.
Use suspend functions or other threading methods to handle database calls.
Room generates code for you, so you don't write raw SQL queries manually.
Summary

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.