Saturday 17 March 2018

Android - Introduction to Room Persistence Library

Sometimes app needs to persist data locally in a structured way. The best example is to cache data which is frequently used, or data which should be accessible even device can not access network. SqLite is the solution for these use cases.

Room Persistence Library makes developer's life easy to integrate sqlite in app. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Today in this tutorial:
  • Introduction of Room
  • How to add Room in the project

Introduction of Room

Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

There are three vital elements in Room.

Database: Contains the database holder and serves as the main access point for the underlying connection to your app's persisted, relational data.
The class that's annotated with @Database should satisfy the following conditions:
    • Be an abstract class that extends RoomDatabase.
    • Include the list of entities associated with the database within the annotation.
    • Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.
At runtime, you can acquire an instance of Database by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().

Entity: Represents a table in the database.

DAO: Contains helper methods to access database and perform operations.

How to add Room in the project

  • Add the google Maven repository 
           To add this in your project open your build.gradle(project level) and add the following code.

allprojects {
    repositories {
        jcenter()
        google()
    }
}
  • Add Architecture Components
          Open your app (module) build.gradle and add the following dependency

 implementation "android.arch.persistence.room:runtime:1.0.0"
 annotationProcessor "android.arch.persistence.room:compiler:1.0.0"

Note: For Kotlin based apps, make sure you use kapt instead of annotationProcessor. You should also add the kotlin-kapt plugin.

Sync your gradle files. 

That's it. Now you are good to go.

I will come up with working demo app using room library in next post. Till then you can look in to SqLite database tutorial. I will replicate this tutorial with Room library in next tutorial. So just go through it and get basic idea about SqLit and demo app.


No comments:

Post a Comment