--

Thursday, 24 May 2018

Kotlin - Chapter 4 - Room DataBase framework

Saving data in local DB using Room

Room persistence library introduced at Google I/O 2017 basically is not a database it just acts as middle man between SQLite and Application layer. By caching required pieces of data from web services.
If the device cannot access the network, the user can still access that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.
Room provides enhanced security, easy access, easy to setup and quick to get started with new database. All the DML (Data Manipulation Language) commands are now annotated except SELECT command which works with @Query.

Components of Room


We have 3 components they are
Entity : a model class annotated with @Entity where all the variable will become column name for the table and name of the model class becomes name of the table.
Database: This is an abstract class where you define all the entities that means all the tables that you want to create for that database.
Dao (Data Access Objects): This is an interface which acts is an intermediary between the user and the database. All the operation to be performed on a table has to be defined here.
Apply the kotlin-kapt plugin in the app.gradle file,
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
Add the kapt dependency in the app.gradle file,
dependencies {
   implementation fileTree(include: ['*.jar'], dir: 'libs')
   implementation "android.arch.persistence.room:runtime:$room_version"
   annotationProcessor "android.arch.persistence.room:compiler:$room_version"
   kapt "android.arch.persistence.room:compiler:$room_version"
...
}
       First of all let’s create our model class where all it’s variable name will become the column name and name of model class will become the table name.

      Now let’s create our Dao interface which contains the list of operation that we would like to perform on table.
Finally let’s create our database with version number.
@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDAOAccess(): IUserDao
}
We can insert test user to Room DB by calling insert() function,

       One great feature that Room supports is LiveData that means you can observe the changes and as soon as any data gets changed in the database you get the response. One more advantage is that LiveData observable are lifecycle aware component which gives response only when your activity or fragment is either in onStart or onResume state.
Now save and run the App. You can download the full source code for this project on GitHub
Happy coding !!!