Sling Academy
Home/Kotlin/Kotlin - Setting Up Room in an Android Project

Kotlin - Setting Up Room in an Android Project

Last updated: December 05, 2024

Kotlin has rapidly become a popular language for Android development. One of its powerful features is the integration with Room, a part of Android Jetpack that offers an abstraction layer over SQLite to smooth out the boilerplate code and streamline interactions with databases. In this article, we'll guide you through the steps required to set up Room in an Android project using Kotlin.

Step 1: Add Room to Your Project

Begin by adding Room to your project dependencies. Open the build.gradle file for your app module and include the following Room components:

dependencies {
    def room_version = "2.4.3"

    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version" // Annotation processor

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:$room_version"
}

Step 2: Enable Kotlin Kapt

To use Room with Kotlin, you need to enable Kotlin KAPT (Kotlin Annotation Processing Tool). This involves applying the kotlin-kapt plugin in your build.gradle:

apply plugin: 'kotlin-kapt'

Step 3: Define Your Entity

In Room, an entity represents a table in your database. Create a data class and annotate it with @Entity to define a table:

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

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

Step 4: Create a Data Access Object (DAO)

DAOs are responsible for defining the methods that access the database. Annotate your interface with @Dao, and use SQL queries to define data operations:

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query

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

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

Step 5: Create the Room Database

Next, create an abstract class that extends RoomDatabase and includes methods to get your DAOs:

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

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

Step 6: Instantiate the Database

You'll need to build the database instance to use Room in your app. It is recommended to use a singleton pattern to avoid having multiple instances:

import android.content.Context
import androidx.room.Room

object DatabaseBuilder {
    private var INSTANCE: AppDatabase? = null

    fun getInstance(context: Context): AppDatabase {
        if (INSTANCE == null) {
            synchronized(AppDatabase::class) {
                INSTANCE = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "app_database"
                ).build()
            }
        }
        return INSTANCE!!
    }
}

Step 7: Using Room in Your Application

Once you have the setup done, interact with your Room database using the DAO objects. For instance, you could insert and retrieve user records as follows:

val db = DatabaseBuilder.getInstance(this)
val userDao = db.userDao()

GlobalScope.launch(Dispatchers.IO) {
    val newUser = User(name = "John Doe", age = 30)
    userDao.insert(newUser)

    val users = userDao.getAllUsers()
    users.forEach {
        Log.d("User: ", "Id: ${it.id}, Name: ${it.name}, Age: ${it.age}")
    }
}

Note: While using coroutines, make sure operations are executed off the main thread. Here, we used Dispatchers.IO for making disk I/O safe.

In conclusion, integrating Room into your Android project using Kotlin enhances your ability to maintain structured and efficient databases. The above guide should set you on course for implementing basic database operations using Room's powerful abstraction over SQLite.

Next Article: Creating Room Entities and Data Classes in Kotlin

Previous Article: Introduction to Room Database for Android (Kotlin)

Series: Kotlin - Interacting with Databases

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin