<h2> <span style="font-size: 26.5pt; font-family: 'Lucida Sans Unicode', sans-serif; letter-spacing: -0.2pt; color: #000080;">Room Persistence Library</span></h2>
<p>Major problem with <strong><span style="color: #0000ff;">SQLite</span></strong> usage is</p>
<ul>
<li>There is no <span style="color: #0000ff;"><strong>compile-time</strong></span> verification of raw SQL queries.For example if you write a SQL query with a wrong <strong><span style="color: #0000ff;">column name</span></strong> that does not exist in real database then it will give exception during run time and you can not capture this issue during <strong><span style="color: #0000ff;">compile time</span></strong>.</li>
</ul>
<p> ;</p>
<ul>
<li>As your schema changes you need to <strong><span style="color: #0000ff;">update</span></strong> the affected SQL queries manually. This process can be time consuming and error prone.</li>
</ul>
<p> ;</p>
<ul>
<li>You need to use lots of <strong><span style="color: #0000ff;">boilerplate code</span></strong> to convert between SQL queries and Java data objects.</li>
</ul>
<p> ;</p>
<p><strong><span style="color: #0000ff;">Room takes care of these concerns for you while providing an abstraction layer over SQLite.</span></strong></p>
<p> ;</p>
<p><amp-youtube layout="responsive" width="1200" height="675" data-videoid="uvoK3Lap_E0" title="Android Architechture Components Example"><a placeholder href="http://youtu.be/uvoK3Lap_E0"><img src="https://i.ytimg.com/vi/uvoK3Lap_E0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Android Architechture Components Example"></a></amp-youtube></p>
<p> ;</p>
<p>By creating an event app i will demonstrate you the working of <strong><span style="color: #0000ff;">insert, update, delete</span></strong><span style="color: #0000ff;"><span style="color: #008000;"> and</span></span><strong><span style="color: #0000ff;"> retrieve</span></strong> functionality using the Room database.<em><strong><span style="color: #000080;">Get </span></strong></em><span style="color: #008000;"><strong>GITHUB</strong></span><em><strong><span style="color: #000080;"><span style="color: #008000;"> </span>code from <a href="https://github.com/arunk7839/EventApp"><span style="color: #008000;">HERE</span>.</a></span></strong></em></p>
<p><span style="color: #000080;"><strong>There are three major components in Room:</strong></span></p>
<p><span style="color: #000080;"><strong>Entity</strong></span> : A class annotated with the <span style="color: #0000ff;"><strong>@Entity</strong></span><a href="https://developer.android.com/reference/android/arch/persistence/room/Entity.html"> </a> annotation is mapped to a table in database. Every entity is persisted in its own table and every field in class represents the column name.</p>
<ul>
<li><span style="color: #0000ff;"><strong>tableName</strong></span> attribute is used to define the name of the table</li>
<li>Every entity class must have at-least one <span style="color: #0000ff;"><strong>Primary Key</strong></span> field, annotated with <span style="color: #0000ff;"><strong>@PrimaryKey</strong></span></li>
<li>Fields in entity class can be annotated with <span style="color: #0000ff;"><strong>@ColumnInfo</strong></span>(name = “name_of_column”) annotation to give specific column names</li>
</ul>
<p><span style="color: #000080;"><strong> DAO</strong></span> : <span style="color: #0000ff;"><strong>Data Access Object</strong></span> is either be an interface or an abstract class annotated with <span style="color: #0000ff;"><strong>@Doa</strong></span> annotation, containing all the methods to define the operations to be performed on data. The methods can be annotated with</p>
<ul>
<li><span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://developer.android.com/reference/android/arch/persistence/room/Query.html">@Query </a> </strong></span>to retrieve data from database</li>
<li><a href="https://developer.android.com/reference/android/arch/persistence/room/Insert.html"><span style="color: #0000ff;"><strong>@Insert</strong></span> </a> to insert data into database</li>
<li><a href="https://developer.android.com/reference/android/arch/persistence/room/Delete.html"><span style="color: #0000ff;"><strong>@Delete</strong></span> </a> to delete data from database</li>
<li><a href="https://developer.android.com/reference/android/arch/persistence/room/Update.html"><span style="color: #0000ff;"><strong>@Update</strong></span> </a> to update data in database</li>
</ul>
<p><strong><span style="color: #0000ff;"><span style="color: #000080;">Note</span>:</span></strong>The result of SQLite queries are composed into <span style="color: #0000ff;"><strong>cursor</strong></span> object, DAO methods abstract the conversion of cursor to <span style="color: #0000ff;"><strong>Entity objects and vice-versa.</strong></span></p>
<p><span style="color: #0000ff;"><strong><span style="color: #000080;">Database</span> :</strong></span> Database is a container for tables. An abstract class annotated with <a href="https://developer.android.com/reference/android/arch/persistence/room/Database.html"><strong>@Database</strong> </a> annotation is used to create a database with given name along with database version.</p>
<ul>
<li><span style="color: #0000ff;"><strong>version</strong></span> = <span style="color: #0000ff;">intValueForDBVersion</span> is used to define the database version</li>
<li><strong><span style="color: #0000ff;">entities</span> </strong>=<span style="color: #0000ff;"> {EntityClassOne.class, &#8230;.}</span> is used to define list of entities for database</li>
</ul>
<h2><span style="color: #000080;">Building an Event App</span></h2>
<p>We will build a Event App that will allow the user to:</p>
<ul>
<li><strong><span style="color: #0000ff;">Create</span></strong> and <span style="color: #0000ff;"><strong>Save</strong></span> event in database</li>
<li><span style="color: #0000ff;"><strong>Display</strong></span> a list of events</li>
<li><span style="color: #0000ff;"><strong>Update</strong></span> and <span style="color: #0000ff;"><strong>Delete</strong></span> event</li>
</ul>
<h2><span style="color: #000080;">Creating New Project</span></h2>
<p>1.In Android Studio, go to <span style="color: #0000ff;"><strong>File </strong><strong>⇒</strong><strong> New Project</strong></span> and fill all the details required to create a new project. When it prompts to select a default activity, select <span style="color: #0000ff;"><strong>Blank Activity</strong></span> and proceed.</p>
<p>2.Open <span style="color: #0000ff;"><strong>build.gradle</strong></span> <span style="color: #0000ff;">(Module:app) <span style="color: #000000;"> and add room library dependency.</span></span></p>
<pre>dependencies {
 
 implementation 'com.android.support:support-v4:26.1.0'
 compile 'com.android.support:design:26.1.0'

 <strong><span style="color: #008000;">//room dependency</span></strong>
 compile 'android.arch.persistence.room:runtime:1.0.0'
 annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'

 <strong><span style="color: #008000;">//recyclerview dependency</span></strong>
 compile 'com.android.support:recyclerview-v7:26.1.0'
 
}</pre>
<h3><span style="color: #000080;">Create Entity</span></h3>
<p>3. Before creating a database, Let&#8217;s create an <span style="color: #0000ff;"><strong>Entity</strong></span>, named as <span style="color: #0000ff;"><strong>Event</strong></span> and later, Objects of this class will be added to database.</p>
<p>To do this:</p>
<ul>
<li>Create a class named <span style="color: #0000ff;"><strong>Event</strong></span>.</li>
<li>Add <strong><span style="color: #0000ff;">@Entity</span></strong> annotation on the class.</li>
<li>Add<span style="color: #0000ff;"><strong> ID, title,description and date fields</strong></span>.</li>
<li><strong><span style="color: #0000ff;">Important:</span></strong> mark at least one field with <span style="color: #0000ff;"><strong>@PrimaryKey</strong></span> annotation.</li>
<li>Use alt+insert to implement constructor, override <strong><span style="color: #0000ff;">getter and setter</span></strong>, and optionally override equals or <strong><span style="color: #0000ff;">toString</span></strong>.</li>
</ul>
<p><strong><span style="color: #000080;">Event.Java</span></strong></p>
<pre>package com.example.lenovo.eventapp.entity;

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;

import static com.example.lenovo.eventapp.entity.Event.TABLE_NAME;


@Entity(tableName = TABLE_NAME)
public class Event {


 public static final String TABLE_NAME = "events";


 @PrimaryKey(autoGenerate = true)
 private int id;
 private String title;
 private String description;
 private String date;

 public Event() {

 }

 @Ignore
 public Event(int id, String title, String description) {
 this.id = id;
 this.title = title;
 this.description = description;
 this.date = date;
 }

 public int getId() {
 return id;
 }

 public void setId(int id) {
 this.id = id;
 }

 public String getDate() {
 return date;
 }

 public void setDate(String date) {
 this.date = date;
 }

 public void setTitle(String title) {
 this.title = title;
 }

 public void setDescription(String description) {
 this.description = description;
 }

 public String getDescription() {
 return description;
 }

 public String getTitle() {
 return title;
 }


 @Override
 public String toString() {
 return "Event{" +
 "id=" + id +
 ", name='" + title + '\'' +
 ", description='" + description + '\'' +
 ", date='" + date + '\'' +
 '}';
 }

}</pre>
<h3><span style="color: #000080;">Creating DAO</span></h3>
<p data-id="2b4490ec4010bc79289802cd29ae51961"><span style="color: #0000ff;"><span style="color: #000000;">4.</span><strong> DAOs</strong></span> define all methods to access database, annotated with<strong><span style="color: #0000ff;"> @Dao </span></strong>annotation. The DAO perform <span style="color: #0000ff;"><strong>CRUD</strong></span> operations on data within a database.</p>
<p data-id="cb31f2e83efc2f765040e254529e5a581">The following code will:</p>
<ul data-id="016587df1af9f6c84aefd44f0131f4f91">
<li>Create an interface, marked with <strong><span style="color: #0000ff;">@Dao </span></strong>annotation.</li>
<li>Add methods for <span style="color: #0000ff;"><strong>CRUD</strong></span> operations.</li>
</ul>
<p><strong><span style="color: #000080;">EventDao.Java</span></strong></p>
<pre>package com.example.lenovo.eventapp.dao;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;

import com.example.lenovo.eventapp.entity.Event;

import java.util.List;


@Dao
public interface EventDao {

 @Query("SELECT * FROM " + Event.TABLE_NAME )
 List<;Event>; getEvents();

 @Insert
 void addEvent(Event event);

 @Delete
 void deleteEvent(Event event);

 @Update
 void updateEvent(Event event);

}</pre>
<h3><span style="color: #000080;">Create Database</span></h3>
<p class="graf" style="background: white; margin: 18.15pt 0cm .0001pt 0cm;">5. Now, we have table defined as Entity and CRUD methods defined via <strong><span style="color: #0000ff;">EventDao</span></strong>.</p>
<p>We will have to:</p>
<ul data-id="d83ab6bf78f9af9140f0f2475ca1a7911">
<li>Create an abstract class <strong><span style="color: #0000ff;">EventDatabse</span></strong> which extends <span style="color: #0000ff;"><strong>RoomDatabase</strong></span>.</li>
<li>Add version and entities to database as <strong><span style="color: #0000ff;">@Database</span></strong>(entities = {Event.class}, version = 1).</li>
<li>Add abstract methods of all DAO&#8217;s where the returned DAO object will be constructed by Room for database interactions.</li>
</ul>
<p data-id="e23af27d8024cfc3eb5d65ed425d3bd41">Some things to remember:</p>
<ul data-id="e5ad1fa4025df4bb7568fdd72492658a1">
<li>Version number is changed to update the database structure, when required in future updates</li>
<li>The database file name must end with the .db extension</li>
<li>Creating instance of database is quite costly so we will apply a <a href="https://en.wikipedia.org/wiki/Singleton_pattern"><strong><span style="color: #0000ff;">Singleton Pattern</span></strong> </a> to create and use already instantiated single instance for every database access.</li>
</ul>
<p><span style="color: #000080;"><strong>EventDatabase.Java</strong></span></p>
<pre>package com.example.lenovo.eventapp.db;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;

import com.example.lenovo.eventapp.dao.EventDao;
import com.example.lenovo.eventapp.entity.Event;


@Database(entities = {Event.class},version = 1)
public abstract class EventDatabase extends RoomDatabase{
 private static final String DB_NAME = "Event_Database.db";
 private static EventDatabase INSTANCE;
 public abstract EventDao eventDao();

 public static EventDatabase getEventDatabase(Context context) {
 if (INSTANCE == null) {
 INSTANCE = Room.databaseBuilder(context, EventDatabase.class, DB_NAME).build();

 }
 return INSTANCE;
 }


}</pre>
<p><span style="color: #000080;"><strong>Note:</strong></span> It is good to note that Room does not allow code execution on Main thread. Instead, <strong><span style="color: #0000ff;">allowMainThreadQueries</span></strong> is used to allow the execution. However, using this is not recommended on real apps. You must perform queries on <strong><span style="color: #0000ff;">AsyncTask (or handler, rxjava),</span></strong> otherwise your application will<strong><span style="color: #0000ff;"> crash</span> </strong>or cause <strong><span style="color: #0000ff;">ANR</span></strong> problems.</p>
<h2><span style="color: #000080;">Implement Database Interactions</span></h2>
<p>6. The below snippet will demonstrate the working of <strong><span style="color: #0000ff;">insert, update, and delete</span></strong> functionality using the Room database.</p>
<p><span style="color: #000080;"><strong>Add Event</strong></span></p>
<pre>private static final String DB_NAME = "Event_Database.db";
private static EventDatabase INSTANCE;
public abstract class EventDatabase extends RoomDatabase{
 private static final String DB_NAME = "Event_Database.db";
 private static EventDatabase INSTANCE;
 public abstract EventDao eventDao();

 public static EventDatabase getEventDatabase(Context context) {
 if (INSTANCE == null) {
 INSTANCE = Room.databaseBuilder(context, EventDatabase.class, DB_NAME).build();

 }
 return INSTANCE;
 }


}
<strong><span style="color: #008000;">//add event into the database</span></strong>
EventDatabase.getEventDatabase(getApplicationContext()).eventDao().addEvent(event);

</pre>
<p><img class="aligncenter wp-image-572 size-large" src="https://c1ctech.com/wp-content/uploads/2018/05/Screenshot_1530085350-576x1024.png" alt="" width="576" height="1024" /><br />
<strong><span style="color: #000080;">Retrieve And Display EventList</span></strong></p>
<pre>private static final String DB_NAME = "Event_Database.db";
private static EventDatabase INSTANCE;

public abstract class EventDatabase extends RoomDatabase{
 private static final String DB_NAME = "Event_Database.db";
 private static EventDatabase INSTANCE;
 public abstract EventDao eventDao();

 public static EventDatabase getEventDatabase(Context context) {
 if (INSTANCE == null) {
 INSTANCE = Room.databaseBuilder(context, EventDatabase.class, DB_NAME).build();

 }
 return INSTANCE;
 }


}
<strong><span style="color: #008000;">//get events from database</span></strong>
List<;Event>; events = EventDatabase.getEventDatabase(getApplicationContext()).eventDao().getEvents();
adapter = new EventsAdapter(events, getApplicationContext());

recyclerView.setAdapter(adapter);

</pre>
<p><img class="alignnone size-medium wp-image-571" src="https://c1ctech.com/wp-content/uploads/2018/05/Screenshot_1530085104-169x300.png" alt="" width="169" height="300" /> <img class="alignnone size-medium wp-image-575" src="https://c1ctech.com/wp-content/uploads/2018/05/Screenshot_1530085640-169x300.png" alt="" width="169" height="300" /></p>
<p><span style="color: #000080;"><strong>Update Event</strong></span></p>
<h3></h3>
<pre>private static final String DB_NAME = "Event_Database.db";
private static EventDatabase INSTANCE;

public abstract class EventDatabase extends RoomDatabase{
 private static final String DB_NAME = "Event_Database.db";
 private static EventDatabase INSTANCE;
 public abstract EventDao eventDao();

 public static EventDatabase getEventDatabase(Context context) {
 if (INSTANCE == null) {
 INSTANCE = Room.databaseBuilder(context, EventDatabase.class, DB_NAME).build();

 }
 return INSTANCE;
 }


}
<strong><span style="color: #008000;">//update event into the database</span></strong>
EventDatabase.getEventDatabase(getApplicationContext()).eventDao().updateEvent(event);</pre>
<p><img class="alignnone size-medium wp-image-573" src="https://c1ctech.com/wp-content/uploads/2018/05/Screenshot_1530085371-169x300.png" alt="" width="169" height="300" /> <img class="alignnone size-medium wp-image-574" src="https://c1ctech.com/wp-content/uploads/2018/05/Screenshot_1530085392-169x300.png" alt="" width="169" height="300" /></p>
<p><strong><span style="color: #000080;">Delete Event </span></strong></p>
<pre>private static final String DB_NAME = "Event_Database.db";
private static EventDatabase INSTANCE;
public abstract class EventDatabase extends RoomDatabase{
 private static final String DB_NAME = "Event_Database.db";
 private static EventDatabase INSTANCE;
 public abstract EventDao eventDao();

 public static EventDatabase getEventDatabase(Context context) {
 if (INSTANCE == null) {
 INSTANCE = Room.databaseBuilder(context, EventDatabase.class, DB_NAME).build();

 }
 return INSTANCE;
 }


}
<strong><span style="color: #008000;">//delete event from database</span></strong>
EventDatabase.getEventDatabase(getApplicationContext()).eventDao().deleteEvent(event);</pre>
<p>7. Open <span style="color: #0000ff;"><strong>activity_main.xml</strong></span> and write the below code .It consist of</p>
<p><strong><span style="color: #0000ff;">Recyclerview</span></strong> : Shows list of events.</p>
<p><span style="color: #0000ff;"><strong>Textview</strong></span> : Which shows <span style="color: #0000ff;"><strong>no event found </strong><span style="color: #000000;">text</span></span> when list contains no item.</p>
<p><strong><span style="color: #0000ff;">FloatingButton</span></strong> : When we click on it ,It opens alertdialog to add event into the database.</p>
<p><span style="color: #0000ff;"><strong>activity_main.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">;

 <;android.support.v7.widget.RecyclerView
 android:id="@+id/recycler_view_list_events"
 android:layout_width="0dp"
 android:layout_height="0dp"
 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintLeft_toLeftOf="parent"
 app:layout_constraintRight_toRightOf="parent"
 app:layout_constraintTop_toTopOf="parent">;

 <;/android.support.v7.widget.RecyclerView>;

 <;TextView
 android:id="@+id/tv_no_events_found"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:fontFamily="sans-serif"
 android:gravity="center"
 android:text="NO EVENTS FOUND!"
 android:textColor="@color/colorPrimaryDark"
 android:textSize="25sp"
 android:visibility="gone" />;

 <;android.support.design.widget.FloatingActionButton
 android:id="@+id/fab_add"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginBottom="16dp"
 android:layout_marginRight="16dp"
 app:elevation="4dp"
 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintRight_toRightOf="parent"
 app:srcCompat="@drawable/ic_add_black_24dp" />;
<;/android.support.constraint.ConstraintLayout>;</pre>
<p>8. Open <strong><span style="color: #0000ff;">event_dialog.xml </span></strong><span style="color: #000000;">and write the below code.On update and add event I have set <strong><span style="color: #0000ff;">event_dialog.xml </span></strong></span>view to alertdialog.</p>
<p><strong><span style="color: #0000ff;">event_dialog.xml</span></strong></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<pre><;?xml version="1.0" encoding="utf-8"?>;
<;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:padding="8dp">;

 <;TextView
 android:id="@+id/dialog_title"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginBottom="10dp"
 android:fontFamily="sans-serif-medium"
 android:text="New Event"
 android:textColor="@color/colorAccent"
 android:textSize="22sp"
 android:textStyle="normal" />;

 <;EditText
 android:id="@+id/edt_title"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@android:color/transparent"
 android:fontFamily="sans-serif"
 android:gravity="top"
 android:hint="Title"
 android:inputType="textCapSentences|textMultiLine"
 android:lines="2"
 android:textColor="@android:color/black"
 android:textColorHint="@color/colorPrimaryDark"
 android:textSize="18sp" />;

 <;EditText
 android:id="@+id/edt_discription"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@android:color/transparent"
 android:fontFamily="sans-serif"
 android:gravity="top"
 android:hint="Discription"
 android:inputType="textCapSentences|textMultiLine"
 android:lines="3"
 android:textColor="@android:color/black"
 android:textColorHint="@color/colorPrimaryDark"
 android:textSize="18sp" />;

 <;RelativeLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content">;

 <;TextView
 android:id="@+id/tv_date"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_marginLeft="8dp"
 android:fontFamily="sans-serif"
 android:textColor="@android:color/black"
 android:textSize="18sp" />;

 <;Button
 android:id="@+id/btn_setdate"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentRight="true"
 android:background="@color/colorAccent"
 android:text="set"
 android:textColor="@android:color/white"
 android:textStyle="bold" />;

 <;/RelativeLayout>;
<;/LinearLayout>;</pre>
<p>9. <span style="color: #0000ff;"><strong>list_item_event.xml </strong><span style="color: #000000;">represents the single list item of recyclerview.<br />
</span></span><br />
<span style="color: #0000ff;"><strong>list_item_event.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginTop="8dp"
 android:padding="8dp">;

 <;LinearLayout
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:orientation="vertical">;

 <;TextView
 android:id="@+id/tv_title"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:fontFamily="sans-serif"
 android:textColor="@android:color/holo_orange_dark"
 android:textSize="20dp"
 android:textStyle="bold" />;

 <;TextView
 android:id="@+id/tv_discription"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="6dp"
 android:fontFamily="sans-serif"
 android:textColor="@android:color/holo_green_light"
 android:textSize="20dp" />;
 <;/LinearLayout>;


 <;TextView
 android:id="@+id/tv_timestamp"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentRight="true"
 android:fontFamily="sans-serif"
 android:textColor="@color/colorAccent"
 android:textSize="20dp"
 android:textStyle="bold" />;


<;/RelativeLayout>;</pre>
<p>10. Creating adapter class for recyclerview, open <strong><span style="color: #0000ff;">EventsAdapter.Java </span></strong><span style="color: #000000;">and write the below code.<br />
</span><br />
<strong><span style="color: #0000ff;">EventsAdapter.Java</span></strong></p>
<pre>package com.example.lenovo.eventapp;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lenovo.eventapp.entity.Event;

import java.util.List;


public class EventsAdapter extends RecyclerView.Adapter<;EventsAdapter.EventViewHolder>; {
 private final Context context;
 private List<;Event>; items;


 public EventsAdapter(List<;Event>; items, Context context) {
 this.items = items;
 this.context = context;

 }

 public class EventViewHolder extends RecyclerView.ViewHolder {
 TextView titleTextView;
 TextView dateTextView;
 TextView descriptionTextView;

 EventViewHolder(View v) {
 super(v);
 titleTextView = (TextView) v.findViewById(R.id.tv_title);
 dateTextView = (TextView) v.findViewById(R.id.tv_timestamp);
 descriptionTextView = (TextView) v.findViewById(R.id.tv_discription);

 }
 }

 @Override
 public EventViewHolder onCreateViewHolder(ViewGroup parent,
 int viewType) {
 View v = LayoutInflater.from(context)
 .inflate(R.layout.list_item_event, parent, false);

 return new EventViewHolder(v);
 }

 @Override
 public void onBindViewHolder(EventViewHolder holder, int position) {
 Event item = items.get(position);
 holder.titleTextView.setText(item.getTitle());
 holder.descriptionTextView.setText(item.getDescription());
 holder.dateTextView.setText(item.getDate());
 }


 @Override
 public int getItemCount() {

 return items.size();
 }


}</pre>
<p>11. Open <strong><span style="color: #0000ff;">RecyclerTouchListener.Java </span></strong><span style="color: #000000;">and write the below code in which </span>I have created custom onClickListener for recyclerview single item <span style="color: #008000;">click.</span><br />
<strong><span style="color: #0000ff;"><br />
RecyclerTouchListener.Java</span></strong></p>
<pre>package com.example.lenovo.eventapp;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;


public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

 private ClickListener clicklistener;
 private GestureDetector gestureDetector;

 public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener) {

 this.clicklistener = clicklistener;
 gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
 @Override
 public boolean onSingleTapUp(MotionEvent e) {
 return true;
 }

 @Override
 public void onLongPress(MotionEvent e) {
 View child = recycleView.findChildViewUnder(e.getX(), e.getY());
 if (child != null &;&; clicklistener != null) {
 clicklistener.onLongClick(child, recycleView.getChildAdapterPosition(child));
 }
 }
 });
 }

 @Override
 public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
 View child = rv.findChildViewUnder(e.getX(), e.getY());
 if (child != null &;&; clicklistener != null &;&; gestureDetector.onTouchEvent(e)) {
 clicklistener.onClick(child, rv.getChildAdapterPosition(child));
 }

 return false;
 }

 @Override
 public void onTouchEvent(RecyclerView rv, MotionEvent e) {

 }

 @Override
 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

 }

 public interface ClickListener {
 void onClick(View view, int position);

 void onLongClick(View view, int position);
 }
}</pre>
<p>12. Open <strong><span style="color: #0000ff;">MainActivity.Java </span></strong><span style="color: #0000ff;"><span style="color: #000000;">and write the below code.The below snippet will demonstrate the working of <span style="color: #0000ff;"><strong>insert, update, delete</strong></span> and <span style="color: #0000ff;"><strong>retrieve list of events</strong></span> functionality using the Room database in DatabaseAsync worker thread.<br />
</span></span><br />
<strong><span style="color: #0000ff;">MainActivity.Java</span></strong></p>
<pre>package com.example.lenovo.eventapp;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.lenovo.eventapp.db.EventDatabase;
import com.example.lenovo.eventapp.entity.Event;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class MainActivity extends AppCompatActivity {

 RecyclerView recyclerView;
 TextView noEventsFound;
 FloatingActionButton fab;
 EventsAdapter adapter;
 List<;Event>; events = new ArrayList<;>;();
 private static TextView tv_date;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 noEventsFound = (TextView) findViewById(R.id.tv_no_events_found);

 recyclerView = (RecyclerView) findViewById(R.id.recycler_view_list_events);

 recyclerView.setItemAnimator(new DefaultItemAnimator());

 recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

 <span style="color: #008000;"><strong>//show list of events if exists in database</strong></span>
 new DatabaseAsync().execute(null, -1, null, null, null);

 <strong><span style="color: #008000;">//shows NO EVENTS FOUND when list is empty</span></strong>
 checkListEmptyOrNot();

 recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
 @Override
 public void onClick(View view, int position) {

 }

 @Override
 public void onLongClick(View view, int position) {

 <strong><span style="color: #008000;">//show Alertdialog to edit or update the event</span></strong>
 showActionsDialog(position);
 }
 }));

 <span style="color: #008000;"><strong>//add listener on FloatingActionButton to add event</strong></span>
 fab = (FloatingActionButton) findViewById(R.id.fab_add);

 fab.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
 //adding new event
 showEventDialog(false, null, -1);
 }
 });
 }

 private class DatabaseAsync extends AsyncTask<;Object, Void, List<;Event>;>; {

 @Override
 protected void onPreExecute() {
 super.onPreExecute();

 <strong><span style="color: #008000;">//Perform pre-adding operation here.</span></strong>
 }

 @Override
 protected List<;Event>; doInBackground(Object... params) {

 Boolean shouldUpdate = (Boolean) params[0];
 int position = (int) params[1];
 String title = (String) params[2];
 String detail = (String) params[3];
 String date = (String) params[4];

 <strong><span style="color: #008000;">//check whether to add add or update event</span></strong>
 if (shouldUpdate != null) {
 <strong><span style="color: #008000;">//update event</span></strong>
 if (shouldUpdate) {
 Event event = events.get(position);
 event.setTitle(title);
 event.setDescription(detail);
 event.setDate(date);

 <span style="color: #008000;"><strong>//update event into the database</strong></span>
 EventDatabase.getEventDatabase(getApplicationContext()).eventDao().updateEvent(event);

 } else {
 <strong><span style="color: #008000;">//add event</span></strong>
 Event event = new Event();
 event.setTitle(title);
 event.setDescription(detail);
 event.setDate(date);

 <strong><span style="color: #008000;">//add event into the database</span></strong>
 EventDatabase.getEventDatabase(getApplicationContext()).eventDao().addEvent(event);
 }

 } else {
 <strong><span style="color: #008000;">//delete event</span></strong>
 if (position != -1) {
 Event event = events.get(position);

 <strong><span style="color: #008000;">//delete event from database</span></strong>
 EventDatabase.getEventDatabase(getApplicationContext()).eventDao().deleteEvent(event);
 }
 }

 <span style="color: #008000;"><strong>//get events from database</strong></span>
 List<;Event>; events = EventDatabase.getEventDatabase(getApplicationContext()).eventDao().getEvents();
 return events;

 }

 @Override
 protected void onPostExecute(List<;Event>; items) {

<strong><span style="color: #008000;">//get list of events from doInBackground()</span></strong>
 events = items;

 adapter = new EventsAdapter(events, getApplicationContext());

 recyclerView.setAdapter(adapter);

 <span style="color: #008000;"><strong>//shows NO EVENTS FOUND when list is empty</strong></span>
 checkListEmptyOrNot();
 }
 }

 private void showActionsDialog(final int position) {
 CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};

 AlertDialog.Builder builder = new AlertDialog.Builder(this);
 builder.setTitle("Choose option");
 builder.setItems(colors, new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 if (which == 0) {

 <strong><span style="color: #008000;">//show Alertdialog to update the event</span></strong>
 showEventDialog(true, events.get(position), position);
 } else {

 <strong><span style="color: #008000;">//delete event from database</span></strong>
 deleteEvent(position);
 }
 }
 });
 builder.show();
 }

 private void deleteEvent(int position) {

 new DatabaseAsync().execute(null, position, null, null, null);
 }

 private void showEventDialog(final Boolean shouldUpdate, final Event event, final int position) {

 LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext());
 View view = layoutInflater.inflate(R.layout.event_dialog, null);

 AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(this);
 alertDialogBuilderUserInput.setView(view);

 TextView dialog_title = (TextView) view.findViewById(R.id.dialog_title);

 final EditText edt_title = (EditText) view.findViewById(R.id.edt_title);

 final EditText edt_discription = (EditText) view.findViewById(R.id.edt_discription);

 tv_date = (TextView) view.findViewById(R.id.tv_date);

 Button btn_setdate = (Button) view.findViewById(R.id.btn_setdate);

 <span style="color: #008000;"><strong>//add listener to button to open datepickerdialog</strong></span>
 btn_setdate.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {

 <span style="color: #008000;"><strong>//open datepickerdialog</strong></span>
 showDateDialog();
 }
 });

 dialog_title.setText(!shouldUpdate ? "New Event" : "Edit Event");

 <span style="color: #008000;"><strong>//in case of update we want all the
 //fields to be set bydefault with text</strong></span>
 if (shouldUpdate &;&; event != null) {
 edt_title.setText(event.getTitle());
 edt_discription.setText(event.getDescription());
 tv_date.setText(event.getDate());
 }

 alertDialogBuilderUserInput
 .setCancelable(false)
 .setPositiveButton(shouldUpdate ? "update" : "add", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialogBox, int id) {

 }
 })
 .setNegativeButton("cancel",
 new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialogBox, int id) {
 dialogBox.cancel();
 }
 });

 final AlertDialog alertDialog = alertDialogBuilderUserInput.create();

 alertDialog.show();

 alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

 <span style="color: #008000;"><strong>// Show toast message when no text is entered</strong></span>
 if (TextUtils.isEmpty(edt_title.getText().toString()) &;&; !TextUtils.isEmpty(edt_discription.getText().toString())) {
 Toast.makeText(MainActivity.this, "Enter title!", Toast.LENGTH_SHORT).show();
 }
 else if (!TextUtils.isEmpty(edt_title.getText().toString()) &;&; TextUtils.isEmpty(edt_discription.getText().toString())) {
 Toast.makeText(MainActivity.this, "Enter description!", Toast.LENGTH_SHORT).show();
 }
 else if (TextUtils.isEmpty(edt_title.getText().toString()) &;&; TextUtils.isEmpty(edt_discription.getText().toString())) {
 Toast.makeText(MainActivity.this, "Enter title and description!", Toast.LENGTH_SHORT).show();
 }
 else {
 alertDialog.dismiss();
 }

 <strong><span style="color: #008000;">//Update or add data into the database only when both field are filled(i.e title,description)</span></strong>
 if (!TextUtils.isEmpty(edt_title.getText().toString()) &;&; !TextUtils.isEmpty(edt_discription.getText().toString())) {

 <strong><span style="color: #008000;">// check if user updating note</span></strong>

 if (shouldUpdate &;&; event != null) {
 <span style="color: #008000;"><strong>// update event</strong></span>
 new DatabaseAsync().execute(shouldUpdate, position, edt_title.getText().toString(), edt_discription.getText().toString(), tv_date.getText().toString());


 } else {
 <span style="color: #008000;"><strong>// create new event</strong></span>
 new DatabaseAsync().execute(shouldUpdate, -1, edt_title.getText().toString(), edt_discription.getText().toString(), tv_date.getText().toString());


 }
 }
 }
 });


 }

 public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
 final Calendar c = Calendar.getInstance();
 int year = c.get(Calendar.YEAR);
 int month = c.get(Calendar.MONTH);
 int day = c.get(Calendar.DAY_OF_MONTH);

 return new DatePickerDialog(getActivity(), this, year, month, day);
 }

 public void onDateSet(DatePicker view, int year, int month, int day) {
 String monthVal, dayVal = "" + day;
 if ((month + 1) <; 10) {
 month += 1;
 monthVal = "0" + month;
 } else {
 month += 1;
 monthVal = "" + month;
 }
 if (day <; 10) {
 dayVal = "0" + day;
 }
 SimpleDateFormat simpledateformat = new SimpleDateFormat("EEEE");
 Date date = new Date(year, month, day - 3);
 String dayOfWeek = simpledateformat.format(date);


 tv_date.setText(dayOfWeek + "\n" + dayVal + "-" + monthVal + "-" + year);

 }
 }

 private void showDateDialog() {
 DialogFragment newFragment = new DatePickerFragment();
 newFragment.show(getSupportFragmentManager(), "datePicker");
 }

 public void checkListEmptyOrNot() {
 if (events.isEmpty())
 noEventsFound.setVisibility(View.VISIBLE);
 else
 noEventsFound.setVisibility(View.GONE);
 }
}</pre>
<p> ;</p>


