Room Database Android Studio

room database android studio

This tutorial describes how to create Room Database in Android Studio. It is part of Local Persistence tutorials. Local Persistence means the storage of data to the device for later use, even after the program that created it has been closed.

Apps that handle non-trivial amounts of structured data can benefit greatly from persisting that data locally. The most common use case is to cache relevant pieces of data. That way, when the device cannot access the network, the user can still browse that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.

I will describe Room Database in Android Studio through a simple To Do list App. In this app we will learn how to insert new row in Room Database. Also, how to update and delete rows from Room Database. Another benefits of our tutorial, is how to use CheckBox inside RecyclerView using Interface class.

Room Database in Simple TO Do List App

Lets start a new android studio project and make the required project settings. First of all we need to add the project dependencies. Open module level gradle file and past the following dependencies.

dependencies {
 
 implementation "androidx.recyclerview:recyclerview:1.2.0-alpha05"
 implementation 'com.rengwuxian.materialedittext:library:2.1.4'
 implementation "androidx.cardview:cardview:1.0.0"
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'android.arch.persistence.room:runtime:1.1.1'
 annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
 implementation 'com.android.support:design:29.0.0'

}

Next change the styles.xml file and set App theme with NoActionBar as the following.

<resources>
<!-- Base application theme. -->
 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
 <item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="menuStyle"
 parent="Theme.AppCompat.Light">
<item name="android:background">@android:color/white</item>

</style>
</resources>

Then create new Image asset and name it “add”. Right click on drawable resource folder the New and select Image Asset. Then select Icon type as “Action Bar and Tap Icons”. Then click on “Clip Art” Button and search for “Post Add”, Select the clip art and click Next Button and then Finish Button.

Create a new resource layout file and name if bar_layout.xml and use the following XML code to add the Button inside ToolBar.

Bar layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar 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="wrap_content"
 app:titleTextColor="@android:color/white"
 android:background="@color/colorAccent"
 style="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
 app:popupTheme="@style/menuStyle"
 android:id="@+id/toolBar"

 >
<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="end"
 android:orientation="vertical">
<FrameLayout
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="@drawable/add"
 android:layout_margin="5dp"
 tools:ignore="UselessParent">


<Button
 android:layout_width="60dp"
 android:layout_height="wrap_content"
 android:background="?attr/selectableItemBackground"
 android:padding="5dp"
 android:textAllCaps="false"
 android:id="@+id/addNewItemActivityBtn"
 android:textColor="@color/colorAccent"
 tools:ignore="HardcodedText" />
</FrameLayout>
</LinearLayout>


</androidx.appcompat.widget.Toolbar>

Add the following XML Code in main_activity.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity">
<include
 android:id="@+id/toolBar"
 layout="@layout/bar_layout"/>

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/swipe">
<androidx.recyclerview.widget.RecyclerView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/toDoRecyclerView"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>



</LinearLayout>

Then create a new resource layout file for items row layout. use the following XML Code.

items row layout
<?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="wrap_content"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:orientation="vertical"
 android:layout_margin="3dp">
<androidx.cardview.widget.CardView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 app:cardElevation="10dp"
 app:cardCornerRadius="5dp"
 app:cardBackgroundColor="@color/colorAccent">
<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical">
<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/toDoItem"
 android:textColor="@android:color/black"
 android:textStyle="bold"
 android:textSize="20dp"
 android:text="To Do Item"
 android:padding="8dp"/>
<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/toDoDate"
 android:textColor="@android:color/black"
 android:textSize="14dp"
 android:text="To Do Date"
 android:padding="8dp"/>
<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/toDoTime"
 android:textColor="@android:color/black"
 android:textSize="12dp"
 android:text="To Do Time"
 android:padding="8dp"/>
<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">
<FrameLayout
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:background="@android:color/white"
 android:layout_weight="1">
<Button
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:text="Edit"
 android:id="@+id/edit"
 android:textAllCaps="false"
 android:textColor="@android:color/black"
 android:background="?attr/selectableItemBackground"
 />
</FrameLayout>
<FrameLayout
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:background="@android:color/white"
 android:layout_weight="1">
<Button
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:text="Delete"
 android:textAllCaps="false"
 android:background="?attr/selectableItemBackground"
 android:textColor="@android:color/black"
 android:id="@+id/delete"
 />
</FrameLayout>
<FrameLayout
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:layout_gravity="center"
 android:background="@android:color/white"
 android:textColor="@color/colorAccent"
 android:layout_weight="1">
<CheckBox
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Complete"
 android:id="@+id/complete"/>
</FrameLayout>




</LinearLayout>

</LinearLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>

Create a new Activity and name it NewItemsActivity. Then add in its XML file the following Code.

new item activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
 android:orientation="vertical"
 tools:context=".NewItemActivityActivity">
<androidx.appcompat.widget.Toolbar
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/colorAccent"
 app:titleTextColor="@android:color/white"
 style="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
 app:popupTheme="@style/menuStyle"
 android:id="@+id/toolBar"/>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@android:color/white"
 android:layout_margin="10dp">
<com.rengwuxian.materialedittext.MaterialEditText
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="TO Do Item"
 android:id="@+id/itemName"
 android:textColor="@color/colorAccent"
 android:textColorHint="@color/colorAccent"
 android:padding="8dp"/>

</FrameLayout>

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
 android:layout_margin="10dp">
<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="To Do Date"
 android:textColor="@android:color/black"
 android:textSize="20dp"
 android:textStyle="bold"
 android:id="@+id/toDoDate"
 android:layout_weight="4"/>
<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Select Date"
 android:id="@+id/toDoDateBtn"
 android:textAllCaps="false"
 android:textColor="@android:color/black"
 android:background="@color/colorAccent"/>
</LinearLayout>

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
 android:layout_margin="10dp">
<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="To Do Time"
 android:textColor="@android:color/black"
 android:textSize="20dp"
 android:id="@+id/toDoTime"
 android:textStyle="bold"
 android:layout_weight="4"/>
<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Select Time"
 android:textAllCaps="false"
 android:id="@+id/toDoTimeBtn"
 android:textColor="@android:color/black"
 android:background="@color/colorAccent"/>
</LinearLayout>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/colorAccent"
 android:layout_margin="20dp">
<Button
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="?attr/selectableItemBackground"
 android:text="Add New Item"
 android:textAllCaps="false"
 android:id="@+id/saveNewItemBtn"
 android:textColor="@android:color/black"
 android:textStyle="bold"/>
</FrameLayout>

</LinearLayout>

Then create a new resource layout file for update existing items. Use the following XML code.

update existing items
<?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="wrap_content"
 android:padding="16dp"
 android:orientation="vertical">
<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@android:color/white"
 android:layout_margin="10dp">
<com.rengwuxian.materialedittext.MaterialEditText
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="TO Do Item"
 android:id="@+id/itemName"
 android:textColor="@color/colorAccent"
 android:textColorHint="@color/colorAccent"
 android:padding="8dp"/>

</FrameLayout>

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
 android:layout_margin="10dp">
<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="To Do Date"
 android:textColor="@android:color/black"
 android:textSize="20dp"
 android:textStyle="bold"
 android:id="@+id/toDoDate"
 android:layout_weight="4"/>
<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Select Date"
 android:id="@+id/toDoDateBtn"
 android:textAllCaps="false"
 android:textColor="@android:color/black"
 android:background="@color/colorAccent"/>
</LinearLayout>

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal"
 android:layout_margin="10dp">
<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="To Do Time"
 android:textColor="@android:color/black"
 android:textSize="20dp"
 android:id="@+id/toDoTime"
 android:textStyle="bold"
 android:layout_weight="4"/>
<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:text="Select Time"
 android:textAllCaps="false"
 android:id="@+id/toDoTimeBtn"
 android:textColor="@android:color/black"
 android:background="@color/colorAccent"/>
</LinearLayout>

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@color/colorAccent"
 android:layout_margin="20dp">
<Button
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="?attr/selectableItemBackground"
 android:text="Update Item"
 android:textAllCaps="false"
 android:id="@+id/saveNewItemBtn"
 android:textColor="@android:color/black"
 android:textStyle="bold"/>
</FrameLayout>

</LinearLayout>

Now, your layout file are ready to create the app next we need to create Room Database.

How to Create Room Database

In this step we need to create a new package and name it myroomdatabase. Then, inside this package create a new java file and name it MyRoomDatabase. This java class will be an abstract class and it will extends RoomDatabase Library. Also, it will annotated with @Database. This annotation requires list of entities, database version and boolean value for export schema. Entities in Room Database represents the tables. see the following Code for more clarification.

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

@Database(entities = {ToDoTable.class},version = 1, exportSchema = false)
public abstract class MyRoomDatabase extends RoomDatabase {


}

Room Data Access Object Interface

The next step is Data Access Object or “Dao”. Dao is a public Interface class the annotated by @Dao. This class contains methods to perform insert, update, reed and delete rows queries. So, create a new Java class and select type as interface class and name it “MyDaoInterfece”. In the following code we will note the each method in the interface has annotated by the query type @Insert, @Update, and @Delete. Also, we can create methods with annotation @Query(“”). Which will take sql query string to select, update or delete specific rows in Table.

package com.androidhands.todolistusingroomdatabase.MRoomDatabase;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

@Dao
public interface MyDaoInterface {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(ToDoTable toDoTable);
@Update(onConflict = OnConflictStrategy.REPLACE)
void update(ToDoTable toDoTable);
@Delete()
void delete(ToDoTable toDoTable);
@Query("SELECT * FROM to_to_table")
List<ToDoTable> collectItems();


}

Note the return type of the method that reads all rows from the table. It returns a list of ToDpTable class. So, we need to create a new java class for Room data table(a new Entity) and name it ToDoTable.

@Query("SELECT * FROM to_to_table")
List<ToDoTable> collectItems();

Entities in Room Database

Entities in database represents the table of database. Entity is a public java class the has annotated by @Entity(tableName = “”) annotation. Each Object inside Room Entity represent a column in the database table. The object data type represents the data type of the column and to specify the column name we need to use @ColumnInfo(name = “”) annotation for each column name. Also each Entity in Room Database requires a Primary Key. We can create a Primary Key for entities by using @PrimaryKey(autoGenerate = true). Note that if you need to make the primary key column auto-incremented cast a true value. The following code is for the project table you can use it inside the ToDoTable java class.

package com.androidhands.todolistusingroomdatabase.MRoomDatabase;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;

import java.sql.Time;
import java.util.Date;

@Entity(tableName = "to_to_table")
public class ToDoTable {

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private int id;
@ColumnInfo(name = "item")
private String item;
@TypeConverters(DateConverter.class)
@ColumnInfo(name = "date")
private Date date;
@TypeConverters(DateConverter.class)
@ColumnInfo(name = "time")
private Date time;
@ColumnInfo(name = "completed")
private boolean completed;


public int getId() {
return id;
}

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

public String getItem() {
return item;
}

public void setItem(String item) {
this.item = item;
}

public Date getDate() {
return date;
}

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

public Date getTime() {
return time;
}

public void setTime(Date time) {
this.time = time;
}

public boolean isCompleted() {
return completed;
}

public void setCompleted(boolean completed) {
this.completed = completed;
}
}

Type Converters

The above table or Entity contains two columns with data type Date. Room provides functionality for converting between primitive and boxed types but doesn’t allow for object references between entities. Sometimes, your app needs to use a custom data type whose value you would like to store in a single database column. To add this kind of support for custom types, you provide a TypeConverter, which converts a custom class to and from a known type that Room can persist. Create a new Java class and name it DateConverter as the following.

package com.androidhands.todolistusingroomdatabase.MRoomDatabase;

import androidx.room.TypeConverter;

import java.util.Date;

public class DateConverter {

@TypeConverter
public static Date toDate(Long timestamp) {
return timestamp == null ? null : new Date(timestamp);
}

@TypeConverter
public static Long toTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}

Now, return to the Database abstract class and complete the code as the following to initiate the database. Note, that we need to add public abstract Dao interface.

package com.androidhands.todolistusingroomdatabase.MRoomDatabase;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

@Database(entities = {ToDoTable.class},version = 1, exportSchema = false)
public abstract class MyRoomDatabase extends RoomDatabase {

public abstract MyDaoInterface myDaoInterface();
public static MyRoomDatabase mInstance;

public static MyRoomDatabase getInstance(Context context){
if (mInstance == null){
mInstance = Room.databaseBuilder(context,MyRoomDatabase.class,"MyDatabaseName")
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.build();
}

return mInstance;
}

}

To Do List Recycler Adapter

Next, We need to create recycler adapter class to hold item. So, create a new java class and name it ToDoRecyclerAdapter and use the following code. Note that each item has CheckBox whic need to create a new interface java class to set on click listener for it.

package com.androidhands.todolistusingroomdatabase;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.androidhands.todolistusingroomdatabase.MRoomDatabase.MyRoomDatabase;
import com.androidhands.todolistusingroomdatabase.MRoomDatabase.ToDoTable;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class ToDoRecyclerAdapter extends RecyclerView.Adapter<ToDoRecyclerAdapter.MyViewHolder> {
private List<ToDoTable> toDoModelList;
private MyRoomDatabase myRoomDatabase;
Context context;
AlertDialog alertDialog;

ToDoRecyclerAdapter(List<ToDoTable> toDoModelList,MyRoomDatabase myRoomDatabase,Context context) {
this.toDoModelList = toDoModelList;
this.myRoomDatabase=myRoomDatabase;
this.context=context;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.to_do_list_item,parent,false);
return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
final ToDoTable toDoModel = toDoModelList.get(position);
holder.toDoItem.setText(toDoModel.getItem());
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
final String strDate = format.format(toDoModel.getDate());
holder.toDoDate.setText(strDate);
final SimpleDateFormat hformate = new SimpleDateFormat("K:mm a",Locale.ENGLISH);
String event_Time = hformate.format(toDoModel.getTime());
holder.toDoTime.setText(event_Time);
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myRoomDatabase.myDaoInterface().delete(toDoModel);
toDoModelList = myRoomDatabase.myDaoInterface().collectItems();
notifyDataSetChanged();
}
});
holder.edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
View nView = LayoutInflater.from(context).inflate(R.layout.updateitem_layout,null);
final EditText itemName = nView.findViewById(R.id.itemName);
itemName.setText(toDoModel.getItem());
final TextView toDoDate = nView.findViewById(R.id.toDoDate);
toDoDate.setText(format.format(toDoModel.getDate()));
final TextView toDoTime = nView.findViewById(R.id.toDoTime);
toDoTime.setText(hformate.format(toDoModel.getTime()));
Button updateItem = nView.findViewById(R.id.saveNewItemBtn);
Button setToDoDate = nView.findViewById(R.id.toDoDateBtn);
setToDoDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
java.util.Calendar calendar = java.util.Calendar.getInstance();
int year = calendar.get(java.util.Calendar.YEAR);
int month = calendar.get(java.util.Calendar.MONTH);
int day = calendar.get(java.util.Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog;
datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
final java.util.Calendar c = java.util.Calendar.getInstance(Locale.ENGLISH);
c.set(java.util.Calendar.YEAR, year);
c.set(java.util.Calendar.MONTH, month);
c.set(java.util.Calendar.DAY_OF_MONTH, dayOfMonth);
final String strDate = format.format(c.getTime());
String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
toDoDate.setText(strDate);
toDoModel.setDate(c.getTime());
}
}, year, month, day);
datePickerDialog.show();

}
});

Button setToDoTime = nView.findViewById(R.id.toDoTimeBtn);
setToDoTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minuts = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(context, R.style.Theme_AppCompat_Dialog
 , new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,hourOfDay);
c.set(Calendar.MINUTE,minute);
c.setTimeZone(TimeZone.getDefault());
SimpleDateFormat hformate = new SimpleDateFormat("K:mm a",Locale.ENGLISH);
String event_Time = hformate.format(c.getTime());
toDoTime.setText(event_Time);
toDoModel.setTime(c.getTime());
}
},hours,minuts,false);
timePickerDialog.show();
}
});

updateItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toDoModel.getDate() == null){
Toast.makeText(context, "Select Date", Toast.LENGTH_SHORT).show();
}else if(toDoModel.getTime() == null){
Toast.makeText(context, "Select Time", Toast.LENGTH_SHORT).show();
}else{
String item = itemName.getText().toString();
if (TextUtils.isEmpty(item)){
Toast.makeText(context, "Insert Item Name", Toast.LENGTH_SHORT).show();

}else{
toDoModel.setItem(item);
myRoomDatabase.myDaoInterface().update(toDoModel);
myRoomDatabase.myDaoInterface().collectItems();
notifyDataSetChanged();
alertDialog.dismiss();

}
}
}
});

builder.setView(nView);
alertDialog = builder.create();
alertDialog.show();

}
});
holder.complete.setChecked(toDoModel.isCompleted());
if (toDoModel.isCompleted()){
holder.toDoItem.setPaintFlags(holder.toDoItem.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}else{
holder.toDoItem.setPaintFlags(0);
}

holder.setItemClickListener(new MyOnClickListener() {
@Override
public void onClickListener(View view, int mPosition) {
CheckBox checkBox = (CheckBox)view;
if (checkBox.isChecked()){
toDoModel.setCompleted(true);
}else{
toDoModel.setCompleted(false);
}
myRoomDatabase.myDaoInterface().update(toDoModel);
myRoomDatabase.myDaoInterface().collectItems();
notifyDataSetChanged();
}
});
}




@Override
public int getItemCount() {
return toDoModelList.size();
}

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView toDoItem,toDoDate,toDoTime;
Button edit,delete;
CheckBox complete;
private MyOnClickListener myOnClickListener;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
toDoItem = itemView.findViewById(R.id.toDoItem);
toDoDate = itemView.findViewById(R.id.toDoDate);
toDoTime = itemView.findViewById(R.id.toDoTime);
edit = itemView.findViewById(R.id.edit);
delete = itemView.findViewById(R.id.delete);
complete = itemView.findViewById(R.id.complete);
complete.setOnClickListener(this);
}

void setItemClickListener(MyOnClickListener myOnClickListener){
this.myOnClickListener = myOnClickListener;
}
@Override
public void onClick(View v) {
this.myOnClickListener.onClickListener(v,getLayoutPosition());
}
}
}

OnClickListener Interface class

package com.androidhands.todolistusingroomdatabase;

import android.view.View;

public interface MyOnClickListener {
void onClickListener(View view,int mPosition);
}

Next, in main activity java class use the following code.

package com.androidhands.todolistusingroomdatabase;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.androidhands.todolistusingroomdatabase.MRoomDatabase.MyRoomDatabase;
import com.androidhands.todolistusingroomdatabase.MRoomDatabase.ToDoTable;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
Button addNewItem;
RecyclerView recyclerView;
public RecyclerView.Adapter adapter;
public List<ToDoTable> toDoModelList = new ArrayList<>();
private MyRoomDatabase myRoomDatabase;
private SwipeRefreshLayout swipeRefreshLayout;
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolBar);
swipeRefreshLayout = findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(this);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("To Do List");
addNewItem = findViewById(R.id.addNewItemActivityBtn);
addNewItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,NewItemActivityActivity.class));
finish();
}
});

myRoomDatabase = MyRoomDatabase.getInstance(this);
recyclerView = findViewById(R.id.toDoRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
collectItems();




}

private void collectItems(){
swipeRefreshLayout.setRefreshing(true);
toDoModelList = myRoomDatabase.myDaoInterface().collectItems();
adapter = new ToDoRecyclerAdapter(toDoModelList,myRoomDatabase,this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}

@Override
public void onRefresh() {
collectItems();

}
}

Finally, in NewItemActivity java class use the following code. And Run the App. Please feel free to type your comment on this article. Also, you can Contact Us.

package com.androidhands.todolistusingroomdatabase;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.androidhands.todolistusingroomdatabase.MRoomDatabase.MyRoomDatabase;
import com.androidhands.todolistusingroomdatabase.MRoomDatabase.ToDoTable;
import com.google.gson.Gson;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class NewItemActivityActivity extends AppCompatActivity {
private MaterialEditText itemName;
private TextView toDoDate,toDoTime;
private MyRoomDatabase myRoomDatabase;
Button saveNewItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_item_activity);
Toolbar toolbar = findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Add New Item");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(NewItemActivityActivity.this,MainActivity.class);
intent.putExtra("mode","new");
startActivity(intent);
finish();
}
});
itemName = findViewById(R.id.itemName);
toDoDate = findViewById(R.id.toDoDate);
toDoTime = findViewById(R.id.toDoTime);

saveNewItem = findViewById(R.id.saveNewItemBtn);
myRoomDatabase = MyRoomDatabase.getInstance(getApplicationContext());
final ToDoTable toDoTable = new ToDoTable();

Button setToDoDate = findViewById(R.id.toDoDateBtn);
setToDoDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
java.util.Calendar calendar = java.util.Calendar.getInstance();
int year = calendar.get(java.util.Calendar.YEAR);
int month = calendar.get(java.util.Calendar.MONTH);
int day = calendar.get(java.util.Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog;
datePickerDialog = new DatePickerDialog(NewItemActivityActivity.this, new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
final java.util.Calendar c = java.util.Calendar.getInstance(Locale.ENGLISH);
c.set(java.util.Calendar.YEAR, year);
c.set(java.util.Calendar.MONTH, month);
c.set(java.util.Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
final String strDate = format.format(c.getTime());
String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
toDoDate.setText(strDate);
toDoTable.setDate(c.getTime());
}
}, year, month, day);
datePickerDialog.show();

}
});

Button setToDoTime = findViewById(R.id.toDoTimeBtn);
setToDoTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minuts = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(NewItemActivityActivity.this, R.style.Theme_AppCompat_Dialog
 , new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,hourOfDay);
c.set(Calendar.MINUTE,minute);
c.setTimeZone(TimeZone.getDefault());
SimpleDateFormat hformate = new SimpleDateFormat("K:mm a",Locale.ENGLISH);
String event_Time = hformate.format(c.getTime());
toDoTime.setText(event_Time);
toDoTable.setTime(c.getTime());
}
},hours,minuts,false);
timePickerDialog.show();
}
});




saveNewItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toDoTable.getDate() == null){
Toast.makeText(NewItemActivityActivity.this, "Select Date", Toast.LENGTH_SHORT).show();
}else if(toDoTable.getTime() == null){
Toast.makeText(NewItemActivityActivity.this, "Select Time", Toast.LENGTH_SHORT).show();
}else{
String item = itemName.getText().toString();
if (TextUtils.isEmpty(item)){
Toast.makeText(NewItemActivityActivity.this, "Insert Item Name", Toast.LENGTH_SHORT).show();

}else{
toDoTable.setItem(item);
toDoTable.setCompleted(false);
myRoomDatabase.myDaoInterface().insert(toDoTable);

}
}

}
});


}
}

Thank You

Related posts

2 Thoughts to “Room Database Android Studio”

  1. uchenne

    this is amazing

Leave a Comment