Kotlin – 52 – Android Room Database with Kotlin

Android Room is a powerful and flexible library that simplifies database operations in Android applications. It provides an abstraction layer over SQLite, making it easier for developers to work with databases using Kotlin or Java. Room’s key features include compile-time SQL query verification and seamless integration with Android’s LiveData and ViewModel components, making it an excellent choice for building robust and data-driven Android apps.

Setting Up Room Database

Before you can start using Android Room in your Kotlin-based Android project, you need to add the necessary dependencies to your app’s build.gradle file:

implementation "androidx.room:room-runtime:2.4.1"
kapt "androidx.room:room-compiler:2.4.1"

Make sure to replace “2.4.1” with the version of Room you want to use. The kapt plugin is required for Room’s annotation processing.

Defining Entities

Entities in Room are used to represent tables in your database. Each entity class corresponds to a table, and each field in the class corresponds to a column in that table. Here’s an example of defining an entity for a “Task” in Kotlin:

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "tasks")
data class Task(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val title: String,
    val description: String,
    val isCompleted: Boolean = false
)

In this example, we’ve created a Task entity with fields for id, title, description, and isCompleted. The @Entity annotation specifies the table name as “tasks,” and @PrimaryKey marks the id field as the primary key.

Creating a DAO (Data Access Object)

A Data Access Object (DAO) in Room defines the methods to interact with the database. DAOs are interfaces or abstract classes that Room implements at compile time. Here’s an example of a TaskDao:

import androidx.room.*

@Dao
interface TaskDao {
    @Query("SELECT * FROM tasks")
    fun getAllTasks(): List<Task>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertTask(task: Task)

    @Update
    suspend fun updateTask(task: Task)

    @Delete
    suspend fun deleteTask(task: Task)
}

In the TaskDao, we’ve defined methods to retrieve all tasks, insert a task, update a task, and delete a task. The @Dao annotation indicates that this is a Data Access Object, and the @Query, @Insert, @Update, and @Delete annotations specify the database operations.

Database Class

To create an instance of the Room database, you need to create an abstract class that extends RoomDatabase and includes an abstract method for each DAO. Here’s an example:

import androidx.room.Database
import androidx.room.RoomDatabase

@Database(entities = [Task::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun taskDao(): TaskDao
}

In this code, we’ve created an AppDatabase class that extends RoomDatabase. It includes an abstract method, taskDao(), which returns the DAO for the Task entity. You also specify the database version and set exportSchema to false to suppress schema export warnings.

Initializing the Database

To initialize your Room database, you typically create an instance of your database class as a singleton. Here’s an example of how to initialize the database in an Android Application class:

import android.app.Application
import androidx.room.Room

class MyApp : Application() {
    companion object {
        lateinit var database: AppDatabase
    }

    override fun onCreate() {
        super.onCreate()

        // Initialize the Room database
        database = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java,
            "my-app-database"
        ).build()
    }
}

In this example, we create a singleton instance of AppDatabase in the MyApp class’s onCreate() method. The Room.databaseBuilder() method is used to build the database instance.

Using Room Database

With your Room database set up, you can easily perform CRUD operations on your data. Here are some examples:

Inserting a Task:
val task = Task(title = "Learn Room", description = "Study Room database", isCompleted = false)
MyApp.database.taskDao().insertTask(task)
Updating a Task:
val updatedTask = task.copy(isCompleted = true)
MyApp.database.taskDao().updateTask(updatedTask)
Deleting a Task:

MyApp.database.taskDao().deleteTask(task)

Querying Tasks:

val allTasks = MyApp.database.taskDao().getAllTasks()

Conclusion

Room Database is a powerful and convenient way to manage your app’s data persistence in Android, especially when combined with Kotlin. By defining entities, creating DAOs, initializing your database, and using Room’s database operations, you can efficiently handle data in your Android application. Room simplifies database-related tasks, promotes clean architecture, and enhances code quality, making it an excellent choice for modern Android app development.