Sling Academy
Home/Kotlin/Kotlin - Using Room for Database Queries and Insertions

Kotlin - Using Room for Database Queries and Insertions

Last updated: December 05, 2024

Kotlin, known for its simplicity and interoperability with Java, is a popular language for Android development. One of the essential components for handling data in Android applications is working with local databases. Room is part of Android's Architecture Components and provides an abstraction layer over SQLite, making database operations more robust and easier to handle. In this article, we will explore how to use Room to perform database queries and insertions.

Introduction to Room

Room is designed to simplify interaction with SQLite databases in Android, eliminate boilerplate code, ensure safer database access, and provide full Out Of the Box support with SQLite. It allows developers to interact with an SQLite database directly, but with simpler code management. Room uses standard SQL queries, but with the added benefit of compile-time verification.

Set Up Room in Your Project

First, ensure that your project is set up to use Kotlin and has the necessary dependencies for Room in the build.gradle:

dependencies {
    def room_version = "2.3.0"
    implementation "androidx.room:room-runtime:
room_version"
    kapt "androidx.room:room-compiler:
room_version"
    // For Kotlin use kapt instead of annotationProcessor
    // optional - RxJava support
    implementation "androidx.room:room-rxjava2:
room_version"
    // optional - Coroutines support
    implementation "androidx.room:room-ktx:
room_version"
    [...] /* Other dependencies */
}

Ensure that the Kotlin Kapt plugin is applied, as it helps in processing annotations for Room.

Defining the Database

Room is composed of three major components - the database, the entities, and the DAO (Data Access Object).

Entities

The Entity represents a table in the Room database. Declare an entity using the @Entity annotation. Here is an example:

@Entity(tableName = "users")
data class User(
    @PrimaryKey val id: Int,
    @ColumnInfo(name = "user_name") val userName: String,
    @ColumnInfo(name = "last_name") val lastName: String
)

DAO (Data Access Object)

DAOs are responsible for defining methods that access your database. It provides a clean API for data access. Here's an example of a DAO:

@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun getAllUsers(): List

    @Insert
    fun insertAll(vararg users: User)

    @Delete
    fun delete(user: User)
}

The above code snippet defines a DAO for managing User entities with methods for querying the entire user table, inserting users, and deleting a user.

Database

Create an abstract class that extends RoomDatabase, annotating it with @Database, and include the entities and the version number of your database:

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

Using Room in the Application

Finally, build your Room database and work with it. You generally create a singleton instance of the database to ensure you don’t have multiple instances of the database opened at the same time:

val db = Room.databaseBuilder(
    applicationContext,
    AppDatabase::class.java, "database-name"
).build()

Performing Queries

Use the DAO to perform queries, for example, fetching users:

val users: List = db.userDao().getAllUsers()

Inserting Data

Insert data by calling insert methods from the DAO:

val user = User(id = 1, userName = "John", lastName = "Doe")
db.userDao().insertAll(user)

Conclusion

Using Room library simplifies tasks around working with databases in Android applications. With built-in support for SQL, compile-time checks, and streamlined annotation-based code, Room ensures your local data storage capabilities are powerful yet easily manageable. Integrating Room is both efficient and effective for reliable database management.

Next Article: Kotlin: Updating and Deleting Records with Room Database

Previous Article: Kotlin - Defining DAO (Data Access Objects) for Room

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