Blog Infos
Author
Published
Topics
, , , ,
Published

This article was originally published on aayushchaudhary.in/blogs

Local database is crucial part in Android Development and Android devices comes with pre-installed SQLite database. SQLite is a lightweight relational database which allows you to run SQL queries. However, SQLite can sometimes be cumbersome to manage directly. This is where Room, the official Object Relational Mapping (ORM) library for Android, comes in. Room offers runtime safety, ease of use, and several other powerful features.

This article is part of Room database series and in this part you’ll learn how to setup Room DB in Android project.

Database integration without Room DB

Before Room database came into picture you’d to write a lot of boilerplate code to setup database. For instance, if you’d want a data class that stores User’s information:

data class User(
     val id: Long,
     val name: String,
     val email: String
)

To store this info into the database then you’d have to perform these steps:

  1. Define and create a SQLiteOpenHelper object and create a new table in SQLiteOpenHelper.onCreate() method using raw SQL queries.
  2. Get a writable instance of database from SQLiteOpenHelper.
  3. Manually serialize User into ContentValues
  4. Insert User into database and make sure you close the connection to database after writing.

These steps require a lot of code and it grows the number of columns you add to User table. You also had to manually maintain the serialization logic.

This is not it, if you want to read data from database then you have to through these steps:

  1. Get a readable database instance from SQLiteOpenHelper
  2. Obtain an instance of Cursor using a SQL query and iterate over the entries stored in the cursor.

Maintaining all this logic by yourself is not optimal. That’s where Room came into picture.

What is Room Database?

The Room persistence library provides an abstraction layer over SQLite, making it easier for developers to access database. Room provides several advantages over directly using SQLite:

  1. Compile-time Verification of SQL Queries: Room verifies your SQL queries at compile time, ensuring that your queries are correct and reducing the risk of runtime errors.
  2. Simplified Database Access: Room simplifies database access by providing a layer of abstraction over SQLite.
  3. Integration with LiveData and Flow: Room supports integration with LiveData and Kotlin’s Flow, making it easier to work with reactive programming.
  4. Built-in Migration Support: Room handles database migrations, making schema updates simpler and safer.

There are three major components in Room library — Database, Data Entity & Data Access Object (DAO). We’ll explore these topics in greater detail later.

Let’s see how you can leverage the Room library with an sample project.

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

,

“Bundle” Up and Save: Powering Room with Bundled SQLite

As part of the Room KMP release, a less known library was significantly updated to support Room KMP, androidx.sqlite. The library was transformed to be beyond a simple backwards compatible Jetpack library for the Android…
Watch Video

"Bundle" Up and Save: Powering Room with Bundled SQLite

Daniel Santiago Rivera
Google

"Bundle" Up and Save: Powering Room with Bundled SQLite

Daniel Santiago Ri ...
Google

"Bundle" Up and Save: Powering Room with Bundled SQLite

Daniel Santiago ...
Google

Jobs

Student Database

We’ll be building students database where you’ll learn how to create DB using Room, creating tables, accessing database, how to handle different type of relationships using Room etc.

Overview of Students’ Database

Before implementing the code, let’s quickly walk through what we are going to build. We will create a student database consisting of four tables: Student, Course, ContactInfo and School.

  • The Student table will store the name of the student and their ID, which will also be the primary key.
  • Each student will be associated with only one school, while a school can have multiple students, indicating a many-to-one relationship between students and schools.
  • Each student will have unique contact info and vice versa.
  • A student can enroll in multiple courses, and a course can have multiple students enrolled, indicating a many-to-many relationship between students and courses.

For simplicity, we will not define the relationship between courses and schools.

Setting up Room database
dependencies {
    // Room
    val room_version = "2.6.1"

    implementation("androidx.room:room-runtime:$room_version")
    annotationProcessor("androidx.room:room-compiler:$room_version")
    // To use Kotlin Symbol Processing (KSP)
    ksp("androidx.room:room-compiler:$room_version")
    // optional - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$room_version")
}

If you’re using kapt then replace ksp with kapt . After adding dependencies you’ve to create a database class. A database class holds the database and maintain connection with your persisted database. The following code defines the StudentDatabase :

@Database(entities = [], version = 1)
abstract class StudentDatabase : RoomDatabase() {
    
}
  • Your database class must be abstract and should extend RoomDatabase.
  • It’ll be annotated by @Database annotation that includes an entities array that lists all of the data entities associated with the database.

Create a single instance of database in Application class.

import android.app.Application
import androidx.room.Room

class StudentApp : Application() {
    companion object {
        private var _database: StudentDatabase? = null
        val database: StudentDatabase? = _database
    }

    override fun onCreate() {
        super.onCreate()
        _database = Room.databaseBuilder(
            this,
            StudentDatabase::class.java,
            "student_database"
        ).build()
    }
}

This article is getting big so we’ll cover creating table and accessing data in next part.

This article is previously published on proandroiddev.com

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
Using annotations in Kotlin has some nuances that are useful to know
READ MORE
blog
One of the latest trends in UI design is blurring the background content behind the foreground elements. This creates a sense of depth, transparency, and focus,…
READ MORE
blog
Now that Android Studio Iguana is out and stable, I wanted to write about…
READ MORE
blog
The suspension capability is the most essential feature upon which all other Kotlin Coroutines…
READ MORE
Menu