Curd Application Using Room Persistence

Hello World! Today i am going to show you how to use Google’s room persistence library to manage all SQLite Operation with in your app.

According to google
The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
In this post I am Just going to Cover CURD Operations ex: CREATE/UPDATE/READ/DELETE.

First Let Understand why we should use these type of libraries.
It check sql queries for error while compling.
Its reduces a lot of code we needed to write for regular operation
Its return data based on our queries directly in objects or we can wrap these results in LiveData, Reactive Observables as well as Cursor.

Lets create a simple project using room persistence library. In this tutorial we are going to create an app in which we can

  • create person
  • delete person
  • update person

And of course fetch list of all person in our database.
curd example using room curd example using room curd example using room

This is my build.gradle (App level)

There are 3 major components in Room:

Entity: Represents a table within the database.
I am going to create a class and annote it with @Entity. This class is also going to serves as our model.
To set table name other then ModelPerson : @Entity(tableName = “tbl_person”)

@PrimaryKey(autoGenerate = true)
This is used to auto generate id

By Using @Embedded we can pass object and room will insert address fields in ModelPerson

Address.class

DAO: Contains the methods used for accessing the database.
We are going to use this class to perform database opeartion.

As we can see that we are using 4 Annotation like @Query, @Insert, @Update and @Delete
PersonDao.class

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

Lets create our database
PersonDb.class

Entities = array of all entites/  class annoted with @Entity

Simple List To show inserted person name,email and age with option to delete and update

AdapterPerson.class

single_person_row.xml

This is going to be our main activty
MainActivity.java

activity_main.xml

alert_add_person.xml
Alert dialog layout to add/update person information.

Utils.java

I am using an image button in toolbar for showing add person dialog
menu_item.xml

styles.xml

strings.xml

Drawable to creating divider line for RecyclerViewline_divider.xml

AndroidManifest.xml

curd example using room
View Code On github

Leave a Reply

Your email address will not be published. Required fields are marked *