Open In App

Overview of Room in Android Architecture Components

Last Updated : 09 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use. But Room makes everything easy and clear to create a Database and perform the operations on it.

Why use Room?

  • Cache the relevant pieces of the data so that when the user’s device is offline, they can still browse and view the content offline.
  • Compile-time SQLite query verification preserves the application from crashing.
  • The annotations which it provides minimizes the boilerplate code.
  • This also provides easy integration with the other Architecture Components like LiveData, LifecycleObserver, etc., You can take codelab provided by Google here.

Difference Between Room and SQLite

Room

SQLite 

No need of writing raw queries. Need to write raw queries.
Compile Time verification of SQL queries. No, compile-time boilerplate verification of SQL queries.
No need of converting the Data to Java Objects. As Room internally maps the Database objects to Java objects. Need to write SQL queries to convert the Data to Java Objects.
This conveniently supports the integration with other Architecture components. This needs a lot of boiler plate code to integrate with the other Architecture Components.
Room provides easier way to work with LiveData and perform the operations. SQLite doesn’t provide a direct way to access the LiveData, it needs external code to be written to access the LiveData.
There is no need to change the code when the database schema gets changes. This needs to change its queries whenever the database schema gets changes

Primary Components of Room

  1. Database Class: This provides the main access point to the underlying connection for the application’s persisted data. And this is annotated with @Database.
  2. Data Entities: This Represents all the tables from the existing database. And annotated with @Entity.
  3. DAO (Data Access Objects): This contains methods to perform the operations on the database. And annotated with @Dao.

Room Library Architecture

From the image below we can conclude the working of the Room database as The application first gets the Data Access Objects (DAOs) associated with the existing Room Database. After getting DAOs, through DAOs it accesses the entities from the Database Tables. And then it can perform the operations on those entities and persist back the changes to the Database.

Steps to implement Room Database in Android Application

Step 1: Create an Empty Activity project

Step 2: Adding the required dependencies

  • Add the following dependencies to the app-level gradle file. By going to ProjectName -> src -> build.gradle.

// room_version may vary

def room_version = “2.3.0”

implementation “androidx.room:room-runtime:$room_version”

kapt “androidx.room:room-compiler:$room_version”

implementation “androidx.room:room-ktx:$room_version”

testImplementation “androidx.room:room-testing:$room_version”

Now creating the components of Room one by one:

Note: Here the entities for every interface and classes created are important and to be taken care of.

Step 3: Creating Data Entity

  • Create a sample Data class naming User.kt.
  • And invoke the following code which contains entities User as an entity, which represents a row and first_name, last_name, age represents column names of the table.

Kotlin




import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
  
@Entity
data class User(
    @PrimaryKey(autoGenerate = true) val uid: Int,
    @ColumnInfo(name = "name") val firstName: String?,
    @ColumnInfo(name = "city") val lastName: String?
)


Step 4: Creating Data Access Objects (DAOs):

  • Now create an interface named as UserDao.kt.
  • And invoke the following code which provides various methods which are used by the application to interact with the user.

Kotlin




import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
  
@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>
  
    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List<User>
  
    @Insert
    fun insertAll(vararg users: User)
  
    @Delete
    fun delete(user: User)
}


Step 5: Creating the Database

  • Now creating the Database which defines the actual application’s database, which is the main access point to the application’s persisted data. This class must satisfy:
  1. The class must be abstract.
  2. The class should be annotated with @Database.
  3. Database class must define an abstract method with zero arguments and returns an instance of DAO.
  • Now invoke the following code inside the AppDatabase.kt file.

Kotlin




import androidx.room.Database
import androidx.room.RoomDatabase
  
@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}


Step 6: Usage of the Room database

  • Inside the MainActivity.kt file we can create a database, by providing custom names for the database.

Kotlin




import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.room.Room
  
class MainActivity : AppCompatActivity() {
  
    // application's Database name
    private val DATABASE_NAME: String = "USER_DATABASE"
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // get the instance of the application's database
        val db = Room.databaseBuilder(
            applicationContext, UserDatabase::class.java, DATABASE_NAME
        ).build()
  
        // create instance of DAO to access the entities
        val userDao = db.userDao()
  
        // using the same DAO perform the Database operations
        val users: List<User> = userDao.getAll()
    }
}


Note: By using this basic knowledge about Room Database one can build a basic CRUD application using Room Database by referring to How to Perform CRUD Operations in Room Database in Android?.



Similar Reads

Overview of WorkManager in Android Architecture Components
Android WorkManager could be thought of as a backgrounding library that is employed to execute background tasks that should run in a guaranteed way but not necessarily immediately. With WorkManager we'll enqueue our backgrounding even when the app isn't running and even when the device is rebooted for a couple of reasons. WorkManager also lets us d
4 min read
Overview of Data Binding in Android Architecture Components
This article describes the idea behind the Data Binding and MVVM design pattern and its components. If you would like to experiment with it hands-on, open an old project with spaghetti code. If you don’t have one, you'll get one from GitHub. Then, attempt to use the MVVM components introduced during this article. In some ways, software development
4 min read
Overview of Navigation in Android Architecture Components
Navigation basically in mobile development refers to the interaction between different screens or pieces of contents within the application. Android Jetpack's architecture Component the Navigation is so powerful, providing a consistent and predictable user experience. The navigation component helps to implement the Navigation between activities and
5 min read
Overview of Paging in Android Architecture Components
The Paging library allows you to load and show pages of data from a bigger dataset that is stored locally or over the network. This method helps your program to make better use of both network bandwidth and system resources. The Paging library's components are built to fit into the suggested Android app architecture, interface well with other Jetpa
3 min read
How to Perform CRUD Operations in Room Database in Android?
Data from the app can be saved on users' devices in different ways. We can store data in the user's device in SQLite tables, shared preferences, and many more ways. In this article, we will take a look at saving data, reading, updating, and deleting data in Room Database on Android. We will perform CRUD operations using Room Database on Android. In
18 min read
How to Build a Grocery Android App using MVVM and Room Database?
In this article, we are going to build a grocery application in android using android studio. Many times we forget to purchase things that we want to buy, after all, we can’t remember all the items, so with the help of this app, you can note down your grocery items that you are going to purchase, by doing this you can’t forget any items that you wa
16 min read
Testing Room Database in Android using JUnit
In this article, we are going to test the Room Database in android. Here we are using JUnit to test our code. JUnit is a “Unit Testing” framework for Java Applications which is already included by default in android studio. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After, etc. Her
5 min read
How to Build a Simple Note Android App using MVVM and Room Database?
Android provides us a feature with which we can store users' data inside their mobile itself with different storage options such as Shared Preferences, SQLite database, and the Room Database. All the data storing techniques are having different use cases. In this article, we will specifically take a look at using a Room Database with Architecture C
19 min read
Android Room Persistence Library in Kotlin
Android Room Persistence Library is one of the sets of libraries provided by Android Jetpack so as to help developers follow the best practices while eliminating boilerplate codes and reducing fragmentation. In Android applications, we often need to store structured data, and persisting that data locally is always a good idea. This way if our appli
5 min read
Android SearchView in Room Database
SearchView in databases is a pretty basic functionality that you can see in most of the applications in your day-to-day life, then why not, you should learn and implement it. it is not too much complicated to implement in your application. There are a lot of easier ways that are how you can implement it. The tasks that you should use to implement f
12 min read
Article Tags :