Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Open in app Sign up Sign in

Search

Getting Started with Room Database in


Android
A Comprehensive Guide to Implementing Room Database

Amit Raikwar · Follow


3 min read · Aug 8, 2023

Listen Share

Introduction:
Local data storage is crucial for many Android applications, allowing them to store
and retrieve data efficiently. In this guide, we will explore Room, a powerful library
that simplifies database management in Android apps. We’ll cover everything from
setting up Room to performing database operations and handling migrations.

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 1/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Structure of using the Room data base in android MVVM project

Section 1: Setting Up Room Database


Step 1: Add Dependencies
Open your app’s `build.gradle` module level file and add the necessary
dependencies for Room and Kotlin Coroutines (for asynchronous operations):

gradle
dependencies {
def roomVersion = "2.4.0" // Check for the latest version
implementation "androidx.room:room-runtime:$roomVersion"
kapt "androidx.room:room-compiler:$roomVersion"
implementation "androidx.room:room-ktx:$roomVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2" // Add
}

OR

For latest android and jetpack compose if its failing with some error we might have
to add ksp() {Kotlin symbol processing}.

Add below dependencies and plugin in build.gradle(Module level).

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 2/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

plugins {
.
.
id "com.google.devtools.ksp"
}

.
.
.

dependencies{
// Room dependency
val room_version = "2.5.2"

implementation("androidx.room:room-ktx:$room_version")
// To use Kotlin annotation processing tool (kapt)
ksp("androidx.room:room-compiler:$room_version")
}

Add below class path for the ksp in build.gradle(app level).

plugins {
id "com.google.devtools.ksp" version "1.8.10-1.0.9" apply false
}

Step 2: Create Entity Class


Define your entity class with annotations to represent a table in the database. For
example, let’s create a `User` entity(Basically consider it as a table in which each
data member are column name):

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

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

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 3/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Step 3: Create DAO (Data Access Object) Interface


Create a DAO interface for defining the database operations. For instance, let’s
create a `UserDao`:

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

@Dao
interface UserDao {

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertUser(user: User)

@Query("SELECT * FROM users")


suspend fun getAllUsers(): List<User>
}

Step 4: Define Database Class


Create an abstract class that extends `RoomDatabase` to define the database
instance and include the entities and DAOs:

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

@Database(entities = [User::class], version = 1)


abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}

Step 5: Initialise Database Instance


In your `Application` class or a relevant entry point, initialize the Room database
instance:

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

class MyApp : Application() {


https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 4/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

companion object {
lateinit var database: AppDatabase
}

override fun onCreate() {


super.onCreate()
database = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java,
"my_database"
).build()
}
}

Section 2: Performing Database Operations


Step 1: Insert Data
To insert a user into the database, you can use the `insertUser` method defined in
the `UserDao`:

val newUser = User(username = "JohnDoe", email = "john@example.com")


MyApp.database.userDao().insertUser(newUser)

Step 2: Retrieve Data


To retrieve all users from the database, use the `getAllUsers` method from the
`UserDao`:

val userList: List<User> = MyApp.database.userDao().getAllUsers()

Please check the demo project for setting up the injectable room database object.

Link to demo project: https://github.com/raikwaramit/RoomDatabaseModule/

GitHub - raikwaramit/RoomDatabaseModule
Contribute to raikwaramit/RoomDatabaseModule development by
creating an account on GitHub.
github.com
https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 5/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Conclusion:
Implementing a Room Database in your Android app can significantly simplify your
data storage needs. With its intuitive setup and powerful features, you can
efficiently manage your app’s local data. By following this guide, you’ve learned how
to set up Room, define entities and DAOs, perform database operations, and handle
migrations.

This guide covered the basics of Room. As you become more comfortable with the
library, you can explore its advanced features, such as database relationships,
LiveData integration, and complex queries.

With Room, managing local data in your Android app has never been easier. Happy
coding!

Android Android Development Room Database Android Storage Sql

Follow

Written by Amit Raikwar


5 Followers

Software engineer with a passion for exploration. Learning new things and sharing engaging articles. Join me
on a journey of learning, growth, and innovation.

More from Amit Raikwar

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 6/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Amit Raikwar

A guide to Android permissions (Jetpack compose)


Accompanist library: Asking permissions in an android ap

4 min read · Aug 13, 2023

Amit Raikwar

Advanced Room Database Architecture for Robust Android Applications


Mastering Complexity: Advanced Techniques for Optimal Room Database Architecture
https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 7/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

4 min read · Aug 13, 2023

Amit Raikwar

Dynamic Animations with Lottie Animation in Jetpack Compose


Enhance your Jetpack Compose UI with Lottie animations using the Airbnb Lottie library

3 min read · Aug 17, 2023

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 8/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Amit Raikwar

Android project resources: A guide for better App UI


All the android resources for UI designing an Android app.

6 min read · Aug 17, 2023

See all from Amit Raikwar

Recommended from Medium

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 9/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Bharath prakash

Getting Started With Room Database in Kotlin + Jetpack Compose ||


MVVM +Dagger Hilt
In this article we will discuss about room hands-on tutorial on room database, which is android
own database library. This is a simple app…

7 min read · Nov 30, 2023

52 1

Majidshahbaz

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 10/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Kotlin Flows With Room Database


In Kotlin we are using state flows to observe data when some change occurs. As state flows are
powerful observers introduced by kotlin to…

· 4 min read · Oct 13, 2023

Lists

ChatGPT
21 stories · 548 saves

Natural Language Processing


1335 stories · 821 saves

Staff Picks
609 stories · 872 saves

Chase

Intro to Room using Jetpack Compose


In this tutorial, you may learn a few tricks that you didn’t know were possible. We will cover the
basics as well as an advanced method of…

11 min read · Dec 22, 2023

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 11/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

16 1

Harshali Sachani in Learn To Earn

Understanding Room migrations


How to deal with manual Room Database migration?

4 min read · Dec 30, 2023

42

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 12/13
31/03/2024, 11:53 Getting Started with Room Database in Android | by Amit Raikwar | Medium

Jorge Luis Castro Medina

Modern Android Development in 2024


Set of good practices, guides, and tools to create modern Android apps in 2024.

18 min read · Feb 12, 2024

2.7K 14

Nimit Raja

Android Hilt, Coroutines, MVVM Flow & Retrofit


By this article I am trying to explain you how to use MVVM(Model View View Model) with
Dependency Injection Hilt with the Combination of…

6 min read · Dec 9, 2023

50 2

See more recommendations

https://amitraikwar.medium.com/getting-started-with-room-database-in-android-fa1ca23ce21e 13/13

You might also like