Room Database in Kotlin - Android Hire
Coding Tutorials

Room Database in Kotlin

Jayant dhingra
Room is part of the Android Architecture Components presented in the Google I/O 2016. It is not an ORM, it is a whole library that allows us to create and manipulate SQLite databases easier, by using annotations we can define our databases, its tables, and operations.

What is Room?

Room will automatically translate these annotations into SQLite instructions/queries to perform the correspondent operations into the DB engine.

Room architecture looks like follow:

The three major components of Room are:

  • Database: It represents the DB, it is an object that holds a connection to the SQLite DB and all the operations are executed through it. It is annotated with @Database.
  • Entity: Represents a table within the Room Database. It should be annotated with @Entity.
  • DAO: An interface that contains the methods to access the Database. It is annotated with @Dao .

Here is an example Room Database in Kotlin

STEP – 1 Add Dependency in app level buid.gradle file

dependencies {
  def room_version = "2.2.5"

  implementation "androidx.room:room-runtime:$room_version"
  kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt 


}

Also we need to add plugin in build.gradle file

apply plugin: 'kotlin-kapt'

Now we want to create a table in which we can store users so we have to do following steps

STEP- 2 Create a kotlin data class

@Entity
data class User(
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?
)

Already mentioned entity is a table in Room database so we want to create a table with table name User (table name will be same as data class name) and will have 3 fields- uid (which will be Primary key), first_name and last_name.

STEP – 3 Create an interface in kotlin

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
           "last_name LIKE :last LIMIT 1")
    fun findByName(first: String, last: String): User

    @Insert
    fun insertAll(vararg users: User)

    @Delete
    fun delete(user: User)
}

@Dao represent the database methods to be used, we use @Insert for inserting data, @delete for deleting data, and @Query to query data.

STEP – 4 Create a database

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

STEP – 5 Call this database in your MainActivity.kt

class MainActivity : AppCompatActivity() {

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

       thread{
       val db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "database-name"
        ).build()  // 1
         
       db.userDao().insertAll(User(1, "Jayant", "Dhingra")) // 2
        }

}
}

Understanding MainActivity

Part 1 => We are creating a Room database builder class then passing the application context , databse class and database name.

Part 2 => We are calling insertAll method from user Dao.

Thats all Folks!!

Jayant dhingra's profile picture

Jayant dhingra

As an enthusiast of stock markets and a skilled developer specializing in Android and augmented reality technologies, I am constantly driven to experiment with code.

Related Posts

7 Top Samsung Galaxy Ring Alternatives for 2025

7 Top Samsung Galaxy Ring Alternatives for 2025

Tired of waiting for the Samsung Galaxy Ring to hit the market? You’re not alone. The smart ring market already has many impressive alternatives available now, despite the buzz around Samsung’s upcoming smart ring. These devices pack advanced health tracking and contactless payment features that might surpass Samsung’s planned offerings. The current lineup of smart […]

What Is Quiet Mode on Instagram and How to Activate It

What Is Quiet Mode on Instagram and How to Activate It

Ever wondered what Quiet Mode on Instagram is all about? This simple yet powerful Instagram feature helps you take a break from the constant buzz of notifications and focus on what truly matters. Whether you’re striving for better work-life balance, dedicating time to studying, or simply trying to disconnect from social media distractions, Quiet Mode […]

How to Make a Bed in Minecraft (Step-by-Step Guide)

How to Make a Bed in Minecraft (Step-by-Step Guide)

A bed in Minecraft is very important. It lets you skip the night and set your spawn point, so if you die, you will return to your bed instead of the original world spawn. This guide will show you how to gather materials, craft a bed, and set your spawn point. We’ll also show you how to customize your bed, build bunk […]

10 Best MMORPG Games For Android

10 Best MMORPG Games For Android

Not too long ago, MMORPG games and powerful gaming consoles were mostly exclusive to PCs. They required high-end graphics and systems to deliver their immersive gameplay. But times have changed. With the rise of gaming-oriented smartphones, you can now enjoy PC-like gaming experiences on your Android device. Thanks to these technological advancements and faster internet […]

Roblox: Fruit Battlegrounds codes (January 2025)

Roblox: Fruit Battlegrounds codes (January 2025)

Fruit Battlegrounds codes are all about getting more gems and help you to shoot up your rank in this One Piece anime-inspired game. This Fruit Battlegrounds was made by Popo developer. It is an action-packed game where players battle it out using unique fruit-based abilities. With constant updates, new fruits, and exciting challenges, it’s a fruity frenzy you won’t […]

Roblox: Ultimate Football Codes (January 2025)

Roblox: Ultimate Football Codes (January 2025)

Want to get some extra items for Ultimate Football in Roblox? You’ve come to the right place! Here’s the latest list of codes to help you score touchdowns and look stylish on the field. These codes offer free rewards such as coins and cosmetics to enhance your gameplay. What are Ultimate Football Codes? Ultimate Football […]

Roblox: Da Hood Codes (January 2025)

Roblox: Da Hood Codes (January 2025)

Are you a fan of Roblox games, in this article we will look at the Roblox Da Hood Codes for December 2024 that will help you unlock exclusive items, improve your gameplay and dominate the streets of Da Hood. You can feel that the game is inspired by the Grand Theft Auto series and there […]