Room Database in Android

Pandiyan Mani
3 min readApr 12, 2023

what is Room Database?

Room is a database layer on top of an SQLite database that handles many tasks to make developers’ life easier.

So lets jump in to the coding part first we need to configure the files neccessary for Room Database.

plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt' // Added Newly
}


implementation "androidx.room:room-runtime:2.4.2"
kapt "androidx.room:room-compiler:2.4.2"
implementation "androidx.room:room-ktx:2.4.2"

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2'

def lifecycle_version = "2.3.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

We need “kapt” dependency to use room annotations. And, we need “ktx” dependency to work with coroutines.

We added the dependencies needed for Room Database and to perform task on background we added coroutines and for Lifecyle we added lifecycle dependencies.

Components Needed for Room:

To use Room library, we need 3 code components. Entity classes, Dao interface and the database class.

Entity classes:

One Entity class for each table. Moreover, to qualify a class as a room entity class, we need to annotate it with @Entity.Holding data is the only purpose of these classes. So, we will create them as Kotlin data classes.

So below will be the table with the Student have multiple column id,name,age.

Columns will have same names as the data class’s variable names.

But, if we want different names we can provide them using @ColumnInfo.

Then, use the @PrimaryKey on the variable selected as the primary key of the table.

If you want the primary key to auto generate set autoGenerate = true

package com.app.roomdatabase

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

@Entity(tableName = "student_table")
data class Student(

@PrimaryKey(autoGenerate = true) var id: Int,
var name: String,
@ColumnInfo(name = "age") var age: String
)

2.Room DAO Interface:

Next, we need to create an interface . And, mark it with @Dao .

DAO stands for “Data Access Object”. This interface is where we define functions to deal with the database.

(you could also define DAO as an abstract class)

package com.app.roomdatabase

import androidx.room.*

@Dao
interface StudentDao {

@Insert
fun insertStudent(student: Student)

@Query("SELECT * FROM student_table")
fun getAllStudent(): List<Student>

@Delete
fun deleteStudent(student: Student)

}

For instance, we have annotated above “insertStudent” function(method) with @Insert . Therefore, room will know that the purpose of that function is inserting data. Room library does not understand the function names. But, room recognizes annotations.

Database Class:

Next, we will create a Room Database class. Create a new Kotlin class naming it as “StudentDatabase”.

This class should be an abstract class. Most importantly, this should extend the “RoomDatabase” class.

package com.app.roomdatabase

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

@Database(entities = [Student::class], version = 1)
abstract class StudentDatabase : RoomDatabase() {
abstract fun studentDao(): StudentDao
}

And, also provide the version number . Database’s version number is very important when we are going to migrate the database.

Now, let’s open the MainActivity.kt . We are going to wirte codes to construct the database.

val db = Room.databaseBuilder(this, StudentDatabase::class.java, "student.db")
.allowMainThreadQueries()
.build()
db.studentDao().insertStudent(studentrecord) // Query for Insert 
for(studentrecord in db.studentDao().getAllStudent()){ // Query for Fetch Data from Database
println("Final Result-->"+studentrecord)
}

Lets see the complete code of MainActivity.kt

package com.app.roomdatabase

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.room.Room

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)


val db = Room.databaseBuilder(this, StudentDatabase::class.java, "student.db")
.allowMainThreadQueries()
.build()

val random1 = (0..100).shuffled().last()
val studentrecord = Student(
name = "Pandiyan",
age = random1.toString()
)
db.studentDao().insertStudent(studentrecord)


for(studentrecord in db.studentDao().getAllStudent()){
println("Final Result-->"+studentrecord)
}
}
}

Happy Coding…

--

--