Insert and fetch records with Room on Android using Kotlin

A step up from SQLite

Introduction:

In this article, we’ll learn about how Android developers can effectively use the Room database to improve data storage processes—and specifically, inserting and fetching records. But before jumping in, let’s first take a look at what we’ve previously been using for data storage in Android.

Before Room:

Before Room, and for a long time, Android developers have relied on SQLite as a primary database. SQLite was mostly easy to use and had some distinct advantages—it allowed data storage in a structured manner, performed better than other databases, and was a lightweight option compared to other 3rd party databases.

But there were also some limitations. First, the database size was restricted to 2GB in most cases. In addition, we needed to remember the queries (like insert, update, delete), and we also needed to write quite a bit of code to make database connections and versions and table column names.

But now we have the Room database, which was launched at Google IO in 2017. Google highly recommend using Room instead of SQLite.

What is Room?

So what is Room? Room is an object mapping library for SQLite. It’s a smooth way to create a database that also eliminates boilerplate code. The Room library provides an abstraction layer over SQLite, which basically means it ends up as an advanced version SQLite.

Basically, with the help of Room database, we can quickly create databases and perform the operations like (create, update, delete, read), and one of the benefits of Room is that we don’t end up with the complex nested objects like with other 3rd party ORM databases.

Now let’s start with the practical example of how we can use the Room Database to insert and fetch records.

Components In Room:

With the Room database, we have 3 components.

  1. The database itself (contains the database holders and server as the main access point and its relational data)
  2. An entity (which represents the table in your database)
  3. DAO (i.e. a Data Access Object, which contains the methods used for accessing the database)

Development Setup:

First, we need to add a dependency for Room in our build.gradle file:

dependencies {
    def room_version = "2.1.0-rc01"

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

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

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

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

    // Test helpers
    testImplementation "androidx.room:room-testing:$room_version"
}

As you can see above, since we’re using Kotlin, we need to use kapt instead of annotationProcessor. so in the case of Kotlin we also need to add a Kotlin plugin:

After a successful setup, we now need to create our components.

First, we need to create a Database class, as shown below:

package com.roomdatabase

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

@Database (entities = [(BookEntity::class)],version = 1)
abstract class AppDb : RoomDatabase() {
    
    abstract fun bookDao(): BookDAO
}

The Database class should be abstract, and it will extend the RoomDatabase() class. Here we also define the database with the annotation @Database, and also define both the entity and version.

Here we also create a function called bookDao which is an abstract function as an abstract class can have only abstract functions, it extends the BookDAO entity and whenever we called bookDao() function it will be called the entity.

Second, we need to create an Entity class (which I defined above) called BookDao. This is basically a table in which we need to define our table’s column:

package com.roomdatabase

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

@Entity
class BookEntity {
    
    @PrimaryKey
    var bookId: Int =0
    
    @ColumnInfo (name ="BookName")
    var bookName:  String =""
    
}

Here we also define our class with the annotation @Entity so we know it’s an entity file. In the above code, we’ve defined the primary key bookId and a column bookName with the help of the annotations.

The third and the final step is to create a DAO interface component for accessing the methods:

package com.roomdatabase

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

@Dao
interface BookDAO
{
    @Insert
    fun saveBooks(book: BookEntity)

    @Query(value = "Select * from BookEntity")
    fun getAllBooks() : List<BookEntity>
}

Project Hierarchy:

That’s it for our setup. Now that our database file is ready, we need to call it on our MainActivity.kt class, and we’ll see the following results:

What I did here—first I created a variable called “db” and created a Room database builder function in which the first parameter is the context, the second parameter is our database class, and the third parameter is the name of our database (this is what you want you to name it during setup).

Insert & Fetch Case:

Now that everything is ready to go, we need to know how to save books in our database. To do this, we create an Entity object, set our desired values, and call our DAO function.

To fetch the records, we just called the getAllBooks() method that we created inside our BookDAO to get all the stored books from the database.

By doing this, we’re able to display the read books with the Book Id and Book Name.

Note:

All of this functionality will be on the other Thread as you can not make operations in on the main-thread like below gist:

 //Insert Case
        val thread = Thread {
            var bookEntity = BookEntity()
            bookEntity.bookId = 1
            bookEntity.bookName = "Kotlin for Android Developer"

            db.bookDao().saveBooks(bookEntity)

            //fetch Records
            db.bookDao().getAllBooks().forEach()
            {
                Log.i("Fetch Records", "Id:  : ${it.bookId}")
                Log.i("Fetch Records", "Name:  : ${it.bookName}")
            }
        }
        thread.start()

Result:

Here’s the fetch records output, you can see the book id and book name which I was saved in our database.

You can check out the sample project as well:

Conclusion:

This article described how you can insert and fetch records using Room Database, It’s an easy and user-friendly and is more simple and easy to learn as well as to do operations like, and we don’t need to remember queries all the time just use annotations and perform various types of operations.

I hope this article is helpful. If you think something is missing, have questions, or would like to give feedback, go ahead and leave a comment below. I’d appreciate the feedback.

I’ve written some other Android-related content, and if you liked what you read here, you’ll probably also enjoy this:

Sharing (knowledge) is caring 😊 Thanks for reading this article. Be sure to clap or recommend this article if you found it helpful. It means a lot to me.

If you need any help then Join me on Twitter, LinkedIn, GitHub, and Subscribe to my Youtube Channel.

Fritz

Our team has been at the forefront of Artificial Intelligence and Machine Learning research for more than 15 years and we're using our collective intelligence to help others learn, understand and grow using these new technologies in ethical and sustainable ways.

Comments 0 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

wix banner square