Work with Room DB Android Kotlin

Shivam Sharma
4 min readJan 10, 2021

--

Room Database is part of Jetpack library. In this blog, I am going to show how to use Room Database in the Android project. I am not going to define the definition of Room Database here.

RoomDatabase provides us Annotations to reduce boilerplate code and help to reduce error(if we write less code less error will come).

In this article, we are going to create a Contact app we have to add a Name and mobile number in DB and show that list in the contact list Screen.

Basically, this app is a Single Activity app where we are using 2 fragments, First is to show a list of saved contact and the other Fragment is to add a contact in the Database. Here we are creating a single ContactViewmodel that ViewModel is used in both fragments.

This is the structure of the app I am following:-

Structure of app

From now onwards we are going to implement all thing step by step:-

Add Room Dependency:-

Add this to build.gradle file

def room_version = "2.2.6"implementation “androidx.room:room-runtime:$room_version”
kapt “androidx.room:room-compiler:$room_version”
// optional — Kotlin Extensions and Coroutines support for Room
implementation “androidx.room:room-ktx:$room_version”
// optional — Test helpers
testImplementation “androidx.room:room-testing:$room_version”

for Implement ViewModel add the following Dependency:-

def lifecycleVersion = '2.2.0'// Lifecycle components
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycleVersion"
// Kotlin components
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines"

After adding dependency click on sync now CTA to get all dependency.

Now we have create table for Database/Entity class

When we are going to create a table for Database we called it Entity class.

We need to set a class name with @Entity(tableName = “contacts”) if we are not giving tableName in Entity then it will automatically take the table name as a class name given by you.

Then we need to assign column name to all variable using @ColumnInfo(name = “name”) columnInfo helps to give table column name.

Then we need to set PrimaryKey using this @PrimaryKey to the variable name and pass autoGenerate = true to set unique Id.

Once Entity class is created then We need to add DAO(Data Access Object)

In this class, we need to create queries to access data from table columns like Insert data into Table and get All data from a table. We need to create DAO class as an interface as the following code. In this, we need to set annotation to describe the function of there work-related like:- @Insert @Query @Delete @Update

Here we need to give annotation to interface @Dao and create a function inside interface according to you required like Insert data into a table or get All data from table set accordingly.

In the insert function pass arguments Entity class name to save a value in Room DB. And add a query to get all contacts from Room DB.

Now create Room Database

In this class, we are going to create a Database as following code:-

Now we go through all code in this class:-

Database class must be abstract and extend with RoomDatabase class. Added annotation at class @Database(entities = [Contacts::class], version = 1) In Database annotation we have to set 2 values First is entities we need to set arrays of Entity class here and the Second value is version set as 1, if we are updating DB schema then we need to update this version number.

Now we need to create a singleton class for Database so that we can use a single instance in-app.

getInstance() will return singleton object. It will create DB when the user opens the app using RoomDatabase builder and set DB name contact_db .

Create Repository

Why do we need to create a repository?

We create this repository to access the database DAO function from here. Pass ContactDao class as arguments.

Here we are using Flow for Observer of data. If anything added in Db needs to update on UI.

suspend is using to tell this function call from another suspend function.

Till here we have done all thing to set up a Database using RoomDatabase

Now only part I am going to tell you how to initialize RoomDatabase once the app is created after that:-

initialize Database from Application class:-

Add this file in <application> tag as name in AndroidManifest.xml file.

Line number 9 is used to initialize the database when the app is created.

repository object is used when we initialize ViewModel in fragment class. we have to pass repository object in Viewmodel class for insert and get contact data from Database.

Here I am not going to print all other files like Fragment, ViewModel class, Adapter class. all these files you guys can get from my github repo.

Hope guys this will help you to understand how to use Room Database in the Android app. I am also in the learning phase if anything is wrong please update me I will update this article asap.

Thanks for reading it 🙂

--

--

Shivam Sharma
Shivam Sharma

No responses yet