Room Database with Kotlin Coroutines in Android
Last Updated :
12 Jun, 2024
This project will be used for the implementation phase. If you have not yet completed the project, you should do so and then return. To keep things simple, the project employs a basic MVVM architecture. The complete code for the implementation mentioned in this blog can be found in the project itself. First, we must configure the Room Database's dependencies as shown below:
implementation("androidx.room:room-runtime:2.6.1")
kapt("androidx.room:room-compiler:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")
Don't forget to include the Kotlin Annotation Processing plugin in your app-level gradle file.
plugins {
... // Other plugins
id("kotlin-kapt")
}
Create the entity that will be our data class in the Room Database, for example, Course.
Kotlin
@Entity
data class GFG(
@PrimaryKey val courseID: Int,
@ColumnInfo(name = "courseName") val name: String?,
@ColumnInfo(name = "courseID") val email: String?,
@ColumnInfo(name = "coursePrice") val avatar: String?
)
For this User, we must create the Dao required for the Room Database, which we will call CourseDao.
Kotlin
@Dao
interface CourseDao {
@Query("SELECT * FROM Course")
suspend fun getAll(): List<Course>
@Insert
suspend fun insertAll(Courses: List<Course>)
@Delete
suspend fun delete(Course: Course)
}
Please keep in mind that we've used the suspend keyword to support Coroutines, so we can call it from a Coroutine or another suspend function. We must now create the AppDatabase that will extend RoomDatabase.
Kotlin
@Database(entities = [Course::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun CourseDao(): CourseDao
}
Following that, we will require a DatabaseBuilder that is a Singleton.
Kotlin
object DatabaseBuilder {
private var INSTANCE: GfgDatabase? = null
fun getInstance(context: Context): GfgDatabase {
if (INSTANCE == null) {
synchronized(GfgDatabase::class) {
INSTANCE = buildRoomDB(context)
}
}
return INSTANCE!!
}
private fun buildRoomDB(context: Context) =
Room.databaseBuilder(
context.applicationContext,
GfgDatabase::class.java,
"geeksforgeeks-example-coroutines"
).build()
}
Then, we'll make a DatabaseHelperImpl implement the DatabaseHelper.
Kotlin
class DatabaseHelperImpl(private val gfgDatabase: GfgDatabase) : DatabaseHelper {
override suspend fun getCourses(): List<Course> = gfgDatabase.CourseDao().getAll()
override suspend fun insertAll(Courses: List<Course>) = gfgDatabase.CourseDao().insertAll(Courses)
}
Again, we used the suspend function so that we could call it from a coroutine or another suspend function. We can pass this instance wherever it is needed, such as to the ViewModel, and make the query to get the users from the database as shown below
Kotlin
class RoomDBViewModel(private val gfgApiHelper: GfgApiHelper, private val dbHelper: DatabaseHelper) :
ViewModel() {
init {
fetchCourses()
}
private fun fetchCourses() {
viewModelScope.launch {
try {
val CoursesFromDb = dbHelper.getCourses()
// here you have your CoursesFromDb
} catch (e: Exception) {
// handler error
}
}
}
Similar Reads
Retrofit with Kotlin Coroutine in Android Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
runBlocking in Kotlin Coroutines with Example Prerequisite: Kotlin Coroutines on AndroidSuspend Function In Kotlin Coroutines As it is known that when the user calls the delay() function in any coroutine, it will not block the thread in which it is running, while the delay() function is called one can do some other operations like updating UI a
5 min read
Chatting Application in Android with Kotlin Building a Real-Time Chat Application can be a great way to dive into Android Development and Firebase. In this article, we will learn to make a basic chat application using Android Studio IDE with Kotlin and real-time chatting using Google's FirebaseFirestore as a database.Pre-requisitesAndroid Stu
7 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
15+ min read
Handle One Time Events in Android with Kotlin Channel You must have used SingleLiveEvent class in android to get rid of multiple occurrences of SnackBars, Toasts, etc on changing device orientation (on rotating device)... If yes, then it's time to say goodbye to SingleLiveEvent Class. We now have a better solution to it using Kotlin's Channels. Before
4 min read
Android - Data Access Object in Room Database Data Access Objects, or DAOs, are used in Room to access your application's persisted data. When compared to query builders or direct queries, they are a better and more modular way to access your database. You should also make a note that a DAO need not be only a class. If it's an abstract class, i
4 min read