Introduction to Room Persistent Library in Android
Last Updated :
23 Jan, 2022
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 can benefit greatly from storing it locally. The most common application is to cache relevant data. As a result, even if the device is unable to connect to the network, the user can still access the content while offline. After the device is brought back online, any user-initiated content changes are synced to the server.
Making More Space in Your Project
In your module’s (app’s) build.gradle file, include the following:
dependencies {
implementation "androidx.room:room-runtime:2.2.5"
kapt "androidx.room:room-compiler:2.2.5"
}
Benefits of Using Room
There are several advantages to using Room over other alternatives such as SQLiteOpenHelper:
- Queries are validated at compile time.
- Cuts down on boilerplate code.
- Simple to grasp and apply.
- Integration with RxJava, LiveData, and Kotlin Coroutines is simple.
Room Components
Room is made up of three major components:
- Database: This contains the database holder and serves as the primary access point for your app’s persisted, relational data.
- Entity: A table in the database that is represented by an entity.
- DAO: This class contains the methods for accessing the database.
The Room database is used by your application to retrieve the data access objects, or DAOs, associated with your database. Each DAO is then used by the app to retrieve entities from the database and save any changes to those entities back to the database. Finally, the app makes use of an entity to retrieve and set values corresponding to table columns in the database.
Database
As previously stated, it contains the database holder and serves as the primary access point for the underlying connection to the persisted, relational data in your app. The class annotated with @Database must meet the following requirements:
- Extend RoomDatabase with an abstract class.
- Within the annotation, include a list of the entities associated with the database.
- Contain an abstract method with no arguments that returns the class annotated with @Dao.
@Database(entities = arrayOf(User::class), version = 1)
abstract class courseDB: RoomDatabase() {
abstract fun courseName(): courseDB
}
GeekTip: When instantiating a RoomDatabase object, you should use the singleton design pattern if your app runs in a single process. Each RoomDatabase instance is reasonably priced, and you rarely require access to multiple instances within a single process.
Entity
A table in a database is represented by an Entity. This class is marked with the @Entity annotation. This class’s data members represent the columns in a table. An entity’s fields must all be public or have getter and setter methods. If all fields are accessible, the entity class should have an empty function Object() { [native code] } or a parameterized function Object() { [native code] } that takes all fields. Partial constructors can also be used in Room. At least one primary key is required for each entity class. To define a single field’s primary key, use the @PrimaryKey annotation, or the primaryKeys attribute of the @Entity annotation for multiple fields. You can also use the @PrimaryKey annotation’s autoGenerate property to assign primary keys automatically.
@Entity
data class User(
@PrimaryKey val uid: Int,
@ColumnInfo(name = "courseName") val firstName: String?,
@ColumnInfo(name = "courseHolder") val lastName: String?
)
To add indices to an entity, use the @Entity annotation’s indices property. You can also create unique indices by setting the @Index annotation’s unique property to true.
@Entity(indices = arrayOf(Index(value = ["courseHolder", "address"])))@Entity(indices = arrayOf(Index(value = ["courseName", "courseHolder"],
unique = true)))
Data Access Object (DAO)
DAOs provide an API for interacting with the database. This is an interface that has the @Dao annotation. This interface’s methods are all used to retrieve data from the database or to make changes to the database. Annotations such as @Query, @Insert, and @Delete are used to identify these methods.
@Dao
interface courseDAO{
@Query("SELECT * FROM course")
fun getAll(): List<GFG>
@Query("SELECT * FROM course WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List<GFG>
@Insert
fun insertAll(vararg courses: User)
@Delete
fun delete(course: Courses)
}
Converting Types
You may need to persist a custom data type in a single database column on occasion. Type converters can be useful in these situations.
class GFG {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return value?.let { Date(it) }
}
@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return date?.time?.toLong()
}
}
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
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 lo
5 min read
How to Include *.so Library in Android Studio?
The SO file stands for Shared Library. You compile all C++ code into the.SO file when you write it in C or C++. The SO file is a shared object library that may be dynamically loaded during Android runtime. Library files are larger, often ranging from 2MB to 10MB in size. As a result, the app becomes
3 min read
JSON Parsing in Android using Retrofit Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specif
6 min read
Introduction to Android Jetpack
The Android support libraries are used in almost all android applications to overcome the compatibility issues across different Android OS versions and devices. These libraries also facilitate users to add various kinds of updated widgets in the application. Over time, these libraries are updated ac
6 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
How to Implement TNImage Library in Android?
Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
3 min read
Getting Started with Paging Library v3 in Android
The RecyclerView used in the Android projects displays a large list of data to the user. However, it is not considered an efficient approach. Fetching a bunch of information from the network and loading it on an application is a vital task. Moreover, while using a mobile application, the user observ
3 min read
Implement App Startup Library in Android
Apps with a shorter startup time have a better user experience. So in this article, we'll talk to you about why the App Startup Library is necessary. Most importantly, we will understand what difficulties it solves and how it aids us in reducing the time it takes for an app to start up. The time it
4 min read
Introduction to Activities in Android
Activity class is one of the very important parts of the Android Component. Any app, don't matter how small it is (in terms of code and scalability), has at least one Activity class. Unlike most programming languages, in which the main() method is the entry point for that program or application to s
6 min read