Education

How to Implement Room Database in Kotlin - DhiWise

logo

DhiWise

June 23, 2021
image
Author
logo

DhiWise

{
June 23, 2021
}

Can you make your android application work even with a poor internet connection?

If yes, is there any persistent library that enables smooth database access by harnessing the power of the SQLite database?

Continue reading this article to get the answer to your questions.

SQLite- The most widely deployed database in the world

SQLite offers the most convenient and safest way to manage information to the database, particularly in the case of read-intensive deployment. It is a reliable, faster, serverless, zero-configuration, database engine written in C language that generally follows PostgreSQL syntax but does not enforce type checking.

SQLite is highly portable and supports many features of MySQL. It could get extensions in whatever programming language you need to access its database. Most importantly, SQLite is embedded in android by default, therefore there is no need to perform any database setup, configuration, and access control task.

However, there are some limitations for using SQLite directly in your app such as,

  • The struggle of verifying SQL queries in compile time.
  • Generates excessive boilerplate code.
  • The complexity of assigning database paths to streamline data migration.

Here the Room database saves you from all these issues and facilitates smooth database access by persisting the data locally.

An app that handles a non-trivial amount of structured data can benefit greatly from persisting data locally and the Room database helps to get that with ease. That means with the Room database your application will work even in the case of internet unavailability.

Let's explore more about the Room database, its architecture and implement the Room database in detail.

What is the Room database?

Room is the SQLite object mapping library which allows more robust database access while harnessing the power of SQLite. In particular, Room provides the following benefits:

  1. Compile-time verification of SQL queries

Any error in the SQLite database query can throw a runtime exception. Using the Room database can explicitly handle this issue as it checks the query at compile time itself. It helps to prevent the application from runtime exceptions.

  1. Reduce boilerplate code.

Room simplifies data manipulation in SQLite by providing an abstraction layer above it. Thus it reduces the efforts of writing unnecessary code for each database query.  So we don’t need to write too much code.

  1. Streamline database migration path

If an application is using a non-Room implementation of SQLite, then it can be easily migrated to ROOM.


Room database architecture

The Room database consists of three main components,

  • Room Database
  • Data Access Objects
  • Entities
Room Db Architecture
Room Db Architecture
  1. Database

To access a database in the Room we need to create a class and annotate it with the database. It also contains DAO(Database  Access Object).

  1. Data Access Object(DAO)

To interact with the Room database we need to create data access objects. It is annotated with @Dao. We can primarily use four annotations inside the DAO.

  • Query: The query is used to run the raw query to target and access specific data.
  • Insert: Insert is used to define a method that allows you to insert an appropriate parameter into the particular database table.
  • Update: The update is used to define a method that updates the database table.
  • Delete: Delete is used to define a method that deletes the record from the database. 
  1. Entities

Entities represent a table in the database. Room Db creates a table for each class that has entity annotation. Each field in the class corresponds to columns in the table. Therefore, the entity classes work as small model classes that don’t contain any logic. 

Well, here is the basic implementation of the Room database.

Basic implementation of Room database

To implement the Room database create a project in android studio and choose a basic activity template.

  1. Adding Dependencies

To use Room in your application add the following dependencies to your app's build.gradle file:

	dependencies {
    def room_version = "2.4.1"

    implementation("androidx.room:room-runtime:$room_version")
    annotationProcessor "androidx.room:room-compiler:$room_version"

    // To use Kotlin annotation processing tool (kapt)
    kapt("androidx.room:room-compiler:$room_version")
   
    // To use Kotlin Symbolic Processing (KSP)
    ksp("androidx.room:room-compiler:$room_version")

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$room_version")

    // optional - RxJava2 support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // optional - RxJava3 support for Room
    implementation "androidx.room:room-rxjava3:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "androidx.room:room-guava:$room_version"

    // optional - Test helpers
    testImplementation("androidx.room:room-testing:$room_version")

     // optional - Paging 3 Integration
    implementation "androidx.room:room-paging:2.4.1"

}


  1. Create an Entity

Before creating a database let’s create an entity. While creating an entity it is necessary to declare the primary key for your table.  

In the code below, each room entity is represented as a class and it is annotated using  @Entity. Also, @PrimaryKey defines the primary key of the table. Further,  you can rename the members without changing the database column name using  @ColumnInfo annotation.

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


  1. Create Data Access Objects 

Data access objects offer abstract access to your app database.  You can define one or more methods to interact with the database of your application with DAO. The code defines how to query, insert, update and delete user objects in the Room database.

The code here shows four annotations: Query, Insert, Update and Delete.

@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)

    @Update
    fun updateUsers(vararg users: User)

    @Delete
    fun delete(user: User)
}


  1. Create Database Class

The following class defines the App Database that holds the database. It acts as the application’s main access point to hold persistent data.

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


The database class must satisfy the following conditions:

  1. The database class must be annotated with the @Database that includes an entities array list of all the entities associated with the database.
  2. The class must be an abstract class that extends RoomDatabase.
  3. For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.

Once you have defined the database, entities, and DAO you can create the instance of the database as,

val db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "database-name"
        ).build()


Then you can use userDao() abstract method to get an instance of DAO.

val userDao = db.userDao()
val users: List = userDao.getAll()


How DhiWise can help you to build an Android application with its built-in support for the Room database 

DhiWise provides built-in support for the Room database so that the code generated with the local database will be in the Room DB. It allows developers to create a data cache to keep the application’s data and take advantage of local persistent data and metaprogramming. 

Overall, it helps you to improve application performance and development efficiency by reducing boilerplate code and run-time errors.

“Finding ways to accelerate your application development process. Start using DhiWise- A new-age application development platform for mobile and web application development, now supporting Kotlin for Android app development”.  


To know more about DhiWise and its Android app builder visit our website today!!

Reference:

https://www.youtube.com/watch?v=lwAvI3WDXBY

https://developer.android.com/training/data-storage/room

https://www.youtube.com/watch?v=yPL13Iwy6oM