Hi android enthusiasts š Iāll be write about, how to use Room Database with MVVM Architecture and using Kotlin Coroutines, happy coding! š„
Update : Now my project implementation clean code with DI using Dagger Hilt. MVVM with DI and old Project MVVM not use DI.
What is Room Database? The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.
The library helps you create a cache of your appās data on a device thatās running your app. This cache, which serves as your appās single source of truth, allows users to view a consistent copy of key information within your app, regardless of whether users have an internet connection.
In this case I will create a NOTE APP using the room library to perform CRUD. here is the flow that we will do.
- Add depedency room+coroutines+livedata+viewmodel
- Create room component (Entity, Dao and Database)
- Create repository and viewmodel to retrieve data from database
- Do action create (insert data), read (show data), delete (delete data) and update (update data)
Please note, when I created this application, I was using Android Studio 4.0.2, I recommend that you use version 4.0.2 or the latest version.
1. Add depedency room+coroutines+livedata+viewmodel
In this project we need to add dependencies room, livedata, etc to build.gradle (Module: app) and plugin kapt like below :
apply plugin: 'kotlin-kapt'
Add the following code to your build.gradle (Module: app)
file, at the end of the dependencies block:
def lifecycle_version = "2.2.0"
def room_version = "2.2.5"
// Material Design
implementation 'com.google.android.material:material:1.2.1'
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
// Annotation processor
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
// Android Room
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
2. Create room components (Entity, Dao and Database)
If you donāt understand about Entity, Dao and Database , I suggest that you read this article. Room, LiveData, and ViewModel by Google Developer
Entity
Room models an SQLite database, and is implemented with an SQLite database as its backend. SQLite databases store their data in tables of rows and columns. Each row represents one entity (or record), and each column represents a value in that entity. For example, an entity for a dictionary entry might include a unique ID, the word, a definition, grammatical information, and links to more info.
Create data class Note.kt, the name of my table is note_table
Dao (data access objects)
To access your appās data using the Room persistence library, you work with data access objects, or DAOs. A set of Dao objects (DAOs) forms the main component of a Room database. Each DAO includes methods that offer abstract access to your appās database.
Create interface NoteDao.kt
You annotate the DAO to specify SQL queries and associate them with method calls. The compiler checks the SQL for errors, then generates queries from the annotations. For common queries, the libraries provide convenience annotations, such as @Insert
, @Delete
, and @Update
and we use suspend
function because we will use kotlin coroutines.
Room Database
Room is a database layer on top of an SQLite database. Room takes care of mundane tasks that you used to handle with an SQLiteOpenHelper
To use Room:
- Create a
public abstract
class that extendsRoomDatabase.
- Use annotations to declare the entities for the database and set the version number.
- Use Roomās database builder to create the database if it doesnāt exist.
- Add a migration strategy for the database. When you modify the database schema, youāll need to update the version number and define how to handle migrations. For a sample, destroying and re-creating the database is a fine migration strategy. For a real app, you must implement a migration strategy. See Understanding migrations with Room.
Create abstract class NoteDatabase.kt and extends RoomDatabase
and use @Database
and name of my db is ānote_database.dbā
3. Repository and ViewModel
Repository
A Repository is a class that abstracts access to multiple data sources. The Repository is not part of the Architecture Components libraries, but is a suggested best practice for code separation and architecture. A Repository
class handles data operations. It provides a clean API to the rest of the app for app data.
A Repository is where you would put the code to manage query threads and use multiple backends, if appropriate. Once common use for a Repository is to implement the logic for deciding whether to fetch data from a network or use results cached in the database.
Create class NoteViewModel.kt
ViewModel
The ViewModel
is a class whose role is to provide data to the UI and survive configuration changes. A ViewModel
acts as a communication center between the Repository and the UI. You can also use a ViewModel
to share data between fragments. The ViewModel
is part of the lifecycle library. For an introductory guide to this topic, see the ViewModel
overview.
Create class NoteViewModel.kt
Because NoteViewModel have constructor (NoteRepository) we need to pass argument to parameter NoteViewModel. the solution is using ViewModelFactory
ViewModelFactory
about viewmodelfactory, you can read this blog
Create NoteViewModelFactory.kt
And weāve finished creating the required classes etc, now we will do CRUD.
4. CRUD (Create, Read, Update and Delete)
Ok,, in this case am just write how implementation viewmodel and calling function insert
, delete
and update
and not for how to design ui, but in my repository, i implement this case with ui and display data with recyclerview too.
Sorry, i am not using depedency injection to pass argument and make my code so boilerplate code, next time, iāll be implements this project with DI, maybe using Kodein or Dagger Hilt.
well, maybe just that, if you want to sample with UI when add, update, delete and show data on recyclerview, you can see my repository on my github about Learn about ā Room + ViewModel + LiveData + RecyclerView (MVVM Architecture)
cheers .. š„š
My old branch (not use DI and need viewModelFactory) : https://github.com/im-o/room-mvvm-architecture/tree/hacktoberfest-2020
And new branch (use Hilt for DI and neednāt use viewModelFactory) : https://github.com/im-o/room-mvvm-architecture/tree/implement-hilt
(I recommended use this)