free geoip
96

How to Use Room Database in Kotlin Android

Room is a powerful persistence library provided by Android Jetpack that offers an abstraction layer over SQLite, allowing for more…

Room is a powerful persistence library provided by Android Jetpack that offers an abstraction layer over SQLite, allowing for more robust database access while harnessing the full power of SQLite. In this article, you will learn how to use Room Database in Kotlin Android with a practical example, including all necessary components like Entity, DAO, Database, and integration in ViewModel.

Room Database in Kotlin Android

Why Use Room Database?

Room handles database operations on a separate thread, provides compile-time validation of SQL queries, and offers LiveData/Flow support for reactive data updates. It’s ideal for applications that require offline storage or caching.

Step-by-Step Implementation

1. Add Room dependencies to your build.gradle:

implementation "androidx.room:room-runtime:2.6.1"
kapt "androidx.room:room-compiler:2.6.1"
implementation "androidx.room:room-ktx:2.6.1"

2. Create an Entity:

@Entity(tableName = "users")
data class User(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val name: String,
    val email: String
)

3. Create DAO (Data Access Object):

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

    @Query("SELECT * FROM users")
    fun getAllUsers(): Flow<List<User>>

    @Delete
    suspend fun delete(user: User)
}

4. Create the Room Database:

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

    companion object {
        @Volatile private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "user_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}

5. Use in Repository and ViewModel:

class UserRepository(private val userDao: UserDao) {
    val allUsers: Flow<List<User>> = userDao.getAllUsers()

    suspend fun insert(user: User) = userDao.insert(user)
    suspend fun delete(user: User) = userDao.delete(user)
}
class UserViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: UserRepository
    val allUsers: LiveData<List<User>>

    init {
        val userDao = AppDatabase.getDatabase(application).userDao()
        repository = UserRepository(userDao)
        allUsers = repository.allUsers.asLiveData()
    }

    fun insert(user: User) = viewModelScope.launch {
        repository.insert(user)
    }

    fun delete(user: User) = viewModelScope.launch {
        repository.delete(user)
    }
}

Bonus: UI Implementation (RecyclerView + ViewModel)

To display the data, you can use a RecyclerView observing the LiveData from the ViewModel and update UI accordingly.

For official documentation and advanced Room features, visit developer.android.com.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *