Android Room Persistence Library in Kotlin
Last Updated :
17 Aug, 2021
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 application crashes or gets restarted the data will not be lost and that data can be retrieved at later times. Especially when we need to show up some relevant information to the user, that needs to be present even in absence of a network, persisting data into the app comes very handy.
Advantages of using Room Persistence Library
Room persistence library is used as an abstraction layer over SQLite for more robust database access. There are several advantages in using this library over SQLite APIs and the ease of using SQLite in a much more natural way is the most prominent one.
- Room has this wonderful feature of compile-time verification of the SQL queries that reduces the chances of run time errors and crashes.
- Room can return Live Data, i.e., get automatic instant updates in database reflected after fetching the data.
- Since Room is an ORM (Object Relational Mapping) library as a user there is no need to convert the Data to Java/Kotlin Objects and vice-versa. As Room internally maps the Database objects to Java objects.
- Room has the convenience of using annotations in place of redundant and boilerplate code sections.
- Yet another amazing feature of Room is that here entire database schema can be changed without changes in the code. or starting from scratch.
- Room has excellent integration with RxJava, Kotlin Coroutines, LifecycleObserver, etc.
Now since we have an idea of the amazing features that come with this library let’s dive deep into this.
Components of Room
Room has three primary components namely Database, Entity (like Tables), and DAO (Data Access Objects). Let us now discuss each of them one by one.
Database
In Room, an abstract class annotated with @Database provides an abstraction layer over the SQLite Database. This component of Room is the major access resource of relation data persisted in the application. The class serving this purpose must be abstract, including a list of entities associated with the database, containing an abstract method with no arguments and return type same as the interface annotated with @Dao. For example, here is a code snippet that shows one such annotated class named AppDatabase that inherits from RoomDatabase.
@Database(entities = [ToDoModel::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun toDoDao(): ToDoDao
// Code Lines
}
Entity
Entity is nothing but a class representing columns of a database table as data fields. This class is annotated with @Entity annotation. All the fields in the class must be accessible, i.e. either public or with getter/setter methods. A constructor also must be present to create entry instances. In Kotlin, the best way is to use a data class that provides the constructor, getter, and setter methods all implemented intrinsically. From the knowledge of SQL, it is known that each entity class must have at least one primary key. For this, that particular field can be annotated with @PrimaryKey annotation to define a single field primary key or in case there are more than one primary key then the attribute of @Entity annotation for multiple fields can be used. We can also annotate fields with @Ignore annotation if we don’t wish to persist in those fields. Here we have a To-do model class as an example with variables title, description, and an id which is autogenerated and acting as the primary key.
@Entity
data class ToDoModel (
var title: String,
var description: String,
// autoGenrate -attribute to
// automatically assign primary keys.
@PrimaryKey(autoGenerate = true)
var id: Long = 0
)
Dao (Data Access Objects)
As discussed above Room allows developers to use SQL queries in a much robust and natural way. Here it is when we see this happening. Dao is an interface annotated with @Dao annotation which possesses all the SQL queries we need to have in usage. This is done using various annotations like @Insert, @Update, @Query, @Delete, etc. that reduce the boilerplate like a magic-making adding or removing queries super easy. It works as an API providing access to the database. These methods are executed on the thread calling them thus we must make sure that they are not called using the main (UI) thread. In case we need to work with multiple entities we need not copy various methods from one Dao to another as it supports inheritance as well. For this just create a generic BaseDao<T> class, and define the various @Insert, @Update, and @Delete methods there. Below is a simple Dao interface having insertion, updating, and querying methods.
@Dao
interface ToDoDao {
@Insert()
suspend fun insertTask(toDoModel: ToDoModel): Long
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateTask(toDoModel: ToDoModel): Int
@Query("SELECT * FROM ToDoModel WHERE isDone == 0")
fun getTask(): LiveData<List<ToDoModel>>
@Query("DELETE FROM ToDoModel WHERE id=:uid")
fun deleteTask(uid: Long)
}
Room Library Architecture
After going through the components of the Room Library we have an idea of how each of them works individually and what are their roles. Now based on this we have this illustration representing their functionalities. We can see Room Database instance acquired by us is used to get access over Dao which in turn has all query functions and control over entities. By using these entities to get and set data as mentioned through the queries in Dao, the data is persisted.

Room Persistence Library Architecture
Implementation and Setup for using Room Database in Applications
For the complete project please refer to this article: How to Build a Grocery Android App using MVVM and Room Database?
Similar Reads
Introduction to Room Persistent Library in Android
Room is a persistence library for Android that is part of Google's Android Jetpack project. According to the documentation, Room acts as an abstraction layer over SQLite, allowing for fluent database access while leveraging SQLite's full power. Apps that deal with a large amount of structured data c
4 min read
JSON Parsing in Android Using Volley Library with Kotlin
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the im
5 min read
Android - JSON Parsing using Retrofit Library with Kotlin
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look
6 min read
Android ListView in Kotlin
ListView in Android is a ViewGroup which is used to display a scrollable list of items arranged in multiple rows. It is attached to an adapter which dynamically inserts the items into the list. The main purpose of the adapter is to retrieve data from an array or a database and efficiently push every
3 min read
Android Motion Layout in Kotlin
MotionLayout is an advanced version of the ConstraintLayout. It is a layout that is designed to simplify the implementation of complex motion and widget animations within the app. Since itâs built as a subclass of ConstraintLayout, it works perfectly with all the usual layout constraints but adds a
5 min read
Android RecyclerView in Kotlin
In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
5 min read
Android LinearLayout in Kotlin
LinearLayout in Android is a ViewGroup subclass, used to arrange child view elements one by one in a singular direction either horizontally or vertically based on the orientation attribute. We can specify the linear layout orientation using the android:orientation attribute. All the child elements a
2 min read
Android Toast in Kotlin
A Toast is a short alert message shown on the Android screen for a short interval of time. Android Toast is a short popup notification which is used to display information when we perform any operation in our app. In this tutorial, we shall not just limit ourselves by creating a lame toast but also
3 min read
Android - Build a Book Library App using Kotlin
There are so many apps that are present in the play store which provides details related to different books inside it. Book Library is considered one of the basic applications which a beginner can develop to learn some basic concepts within android such as JSON parsing, using recycler view, and othe
11 min read
Android YoutubePlayerView Library with Kotlin
Many applications display videos within their application for displaying video content directly from YouTube. For displaying these YouTube videos within android applications we have to integrate YouTube Player View within the android application. In this article, we will take a look at How to Implem
5 min read