Logo

dev-resources.site

for different kinds of informations.

Understanding Room Database in Android: A Beginner's Guide

Published at
1/4/2025
Categories
android
kotlin
mobile
beginners
Author
harsh_lade
Categories
4 categories in total
android
open
kotlin
open
mobile
open
beginners
open
Author
10 person written this
harsh_lade
open
Understanding Room Database in Android: A Beginner's Guide

Introduction

Room Database is an essential topic in Android Development, enabling developers to store and manage data efficiently. It acts as an abstraction layer over SQLite, simplifying database operations and making data management more developer-friendly. In this article, we will explore Room Database step by step, with practical examples to help you understand its implementation.


Why to use Room Database

  • Abstraction Layer: Room provides an abstraction layer over SQLite, allowing developers to write simpler and more idiomatic Kotlin code.
  • Compile-Time Verification: Room validates queries and schema definitions at compile time, reducing runtime errors and enhancing reliability.

Key Concepts/Terminologies

  • Entities: Represents table in your Database.
  • Dao (Data Access Object): Defines the operations with the Database.
  • Database: Acts as the database holder and contains all the tables.

Step-by-Step Implementation.

Let’s walk through the implementation process using an example of a User Database.

Step 1: Add Plugin

To get started, you need to add a pluginβ€”either kapt or ksp. This plugin will help the compiler to understand the quotations that we will use.

  • ksp (Kotlin Symbol Processing): Faster and more efficient for annotation processing.
  • kapt (Kotlin Android Processing Tool): Traditional and widely used.

You can choose either ksp or kapt.
If you want to learn about ksp and kapt then you can refer to the official documentation. For now, you can continue.
In this example, we will use kapt.

  • Adding Kapt

Open your build.gradle.kts (module level) and add the following line inside plugins block:

plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.jetbrains.kotlin.android)

    id("kotlin-kapt") // Add this line
}
Enter fullscreen mode Exit fullscreen mode
  • Adding ksp

Open build.gradle.kts (project level) in you project files. Here you have to add plugin for ksp.

plugins {
    //other plugins...

    //Your to add this. The version should be same as your kotlin (for first). 
    //For eg. you have kotlin version 1.9.22 then the version for ksp plugin should be 1.9.22-x.x.x
    id("com.google.devtools.ksp") version "1.9.22-1.0.17" apply false
}
Enter fullscreen mode Exit fullscreen mode

Now, open you build.gradle.kts (module level) add this line in plugins block:

plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.jetbrains.kotlin.android)

    id("com.google.devtools.ksp") // Add this line
}
Enter fullscreen mode Exit fullscreen mode

Sync your project after adding the plugin.


Step 2: Add Dependencies

Add the required dependencies for Room in your build.gradle.kts (module level) file:

dependencies{
    implementation("androidx.room:room-runtime:2.6.1") 
    //For Kotlin extension coroutines for room.
    implementation("androidx.room:room-ktx:2.6.1")
    //To use kotlin annotation processor.
    kapt("androidx.room:room-compiler:2.6.1")
}
Enter fullscreen mode Exit fullscreen mode

Ensure you use the latest versions of these dependencies. After adding these dependencies, sync your project.


Step 3: Creating your First Table/Entity

Create the First Table inside the Database. To create one, define a data class annotate it with @Entity and give a name. Each entity must have at least one primary key annotate by @PrimaryKey, you can set it to auto-generate so it will get generated automatically.

@Entity(tableName="user_table")
data class User(
    @PrimaryKey(autoGenerate = true) val id:Int, //Define a primary key in table
    val name:String,
    val contact:Long
)
Enter fullscreen mode Exit fullscreen mode

Step 4: Define a DAO Interface

DAO (Data Object Interface) defines the operations you can perform on the database such as:

  • Insert
  • Delete
  • Query
  • Update

Create an interface annotate it by @Dao and give it a name (UserDao, in this case).

@Dao
interface UserDao {
    @Insert //Define more methods as per your use
    suspend fun insert(user: User)

    //we can write any SQL query.
    @Query("select * from user_table order by id ASC")
    fun getData(): Flow<List<User>>
}
Enter fullscreen mode Exit fullscreen mode

Here, getAllUsers() retrieves all users from the user_table in ascending order.


Step 5: Define a Database

Now, we will implement a database. Create an abstract class that will implement RoomDataBase(). Annotate it by @Database inside the annotation you will have to give all the Table/Entity names you are using and a version (we will update this version if we want to update anything in our database).

example:

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

Step 6: Initializing Room

Finally, initialize the Room database in your application. Use the Room.databaseBuilder() method to create an instance.

val db=Room.databaseBuilder(
    context,
    AppDatabase::class.java, //We have to give our database class (abstract class in step 5)
    "app_database" //you can give any name to database.
).build()
val userDao=db.userDao()//It is our dao.
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we explored the fundamentals of Room Database, including adding plugins, dependencies, entities, DAOs, and initializing the database. In the next article, we will learn how to perform operations such as adding and retrieving data from the database.

Stay tuned for more practical insights into Android Development!

kotlin Article's
30 articles in total
Favicon
Using SVGs on Canvas with Compose Multiplatform
Favicon
Kotlin Generics Simplified
Favicon
Understanding Quick Sort in Kotlin : A Beginner's Guide
Favicon
Understanding Selection Sort in Kotlin: A Beginner's Guide
Favicon
Wednesday Links - Edition 2025-01-08
Favicon
Testing Pi Logic integrations.
Favicon
Understanding (a bit of) the Gradle Kotlin DSL
Favicon
Android TreeView(Hierarchy based) with Kotlin
Favicon
Creando un notebook con Jupyter y Kotlin
Favicon
Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 3/3)
Favicon
Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 2/3)
Favicon
Understanding Room Database in Android: A Beginner's Guide
Favicon
Fixing Rounded Navigation Bar Corner Padding in Jetpack Compose
Favicon
Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 1/3)
Favicon
My conference year
Favicon
Authentication in Android Project with Firebase.
Favicon
Learn Firebase for Android Development from Scratch, a beginner guide.
Favicon
🧹 Improve Filtering with the Predicate Interface!
Favicon
How to make the best of a slow machine running on limited resources with a Windows environment as a Java Engineer
Favicon
How to implement detekt in Spring Boot + Kotlin + Gradle project
Favicon
How to Create and Publish an Android Library for Beginners
Favicon
Pub-sub Redis in Micronaut
Favicon
ISBN Stacks β€” A look at a possible Spring Application implementation without annotations
Favicon
Protecting Applications with Kong security plugins and using StatsD to monitor system states β€” A healthy camera story
Favicon
Configurable Kong API Gateway with Micronaut Services in Kotlin β€” A very odd Yucca tribute concert
Favicon
Learning AWS with Localstack and Reactive Kotlin β€” A stamps and coins implementation
Favicon
Coroutines, Distributed Cache, Resilience, and Replication in Kotlin β€” Making a VMA’s application
Favicon
From Paris to Berlin β€” Creating Circuit-Breakers in Kotlin
Favicon
Understanding Merge Sort in Kotlin: A Beginner's Guide
Favicon
City Library β€” An advanced guide to Circuit Breakers in Kotlin

Featured ones: