How to add a task in todo list app using floating action button| Todo Android app using Node JS and REST API | Part 5

In this series of todo app using rest API, today we will discuss how to add a task using floating action button and Node JS REST API.

If you’re new then go through the previous parts of this project otherwise you will not understand anything about this project.

Part 1 (CLICK HERE)

Part 2 (CLICK HERE)

Part 3 (CLICK HERE)

Part 4 (CLICK HERE)

Overview

Add Dependency

dependencies {
……………

implementation ‘com.android.volley:volley:1.1.1’
implementation ‘de.hdodenhof:circleimageview:3.1.0’
implementation ‘com.squareup.picasso:picasso:2.71828’

implementation ‘com.google.android.material:material:1.2.1’
implementation ‘com.android.support:design:30.1.0’
implementation ‘androidx.recyclerview:recyclerview:1.1.0’
implementation ‘androidx.cardview:cardview:1.0.0’

}

API (Node JS)

In the node js, we need to code for adding a task, also store that task in the database.

In node js:

//desc Create new todo task

// method POST

router.post(‘/’, auth, async(req, res, next) =>{

try{

const snapShot = await Snapshot.create({title: req.body.title, description: req.body.description, user: req.user.id});

if(!snapShot){

return res.status(400).json({

success: false,

msg: ‘Something went wrong!’

});

}

res.status(200).json({

success: true,

snapshot: snapShot,

msg: ‘Successfully created..’

});

} catch (error){

next(error);

}

})

//desc Fetch all todos

//method GET

router.get(‘/’, auth, async(req, res, next) => {

try {

const snapshot = await Snapshot.find({user: req.user.id, finished: false});

if(!snapshot){

return res.status(400).json({

success: false,

msg: ‘Something error happened!’

});

}

res.status(200).json({

success: true,

count: snapshot.length,

snapshots: snapshot,

msg: ‘Successfully fetched..’

});

} catch (error) {

next(error);

}

})

Home Fragment XML

  • In home fragment XML file add our recyclerview, where we display our tasks when we add a task using rest API.

<?xml version=”1.0" encoding=”utf-8"?>
<RelativeLayout 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:background=”@color/white”
xmlns:app=”http://schemas.android.com/apk/res-auto"
tools:context=”.Fragments.HomeFragment”>

<androidx.recyclerview.widget.RecyclerView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/recyclerView”
android:layout_marginTop=”5dp”
android:layout_alignParentTop=”true”/>

<ProgressBar
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/progressBar”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true”
android:visibility=”gone”
android:indeterminateTint=”@android:color/holo_blue_dark”/>

<ImageView
android:layout_width=”250dp”
android:layout_height=”250dp”
android:src=”@drawable/box”
android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:id=”@+id/empty_image”
android:visibility=”gone”
app:tint=”@color/backgroundMain” />
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/empty_text”
android:text=”Sorry, No Task Found”
android:textAlignment=”center”
android:textSize=”17sp”
android:fontFamily=”@font/ubuntu_bold”
android:textColor=”@color/backgroundMain”
android:layout_marginTop=”-40dp”
android:layout_below=”@+id/empty_image”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true”
android:visibility=”gone”
android:padding=”5dp”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/empty_text2"
android:text=”@string/add_a_task_click_button”
android:textAlignment=”center”
android:textSize=”17sp”
android:fontFamily=”@font/ubuntu”
android:textColor=”@color/backgroundMain”
android:layout_below=”@+id/empty_text”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true”
android:visibility=”gone”
android:padding=”5dp”/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:backgroundTint=”@color/buttonColor”
android:src=”@drawable/ic_add”
android:id=”@+id/add_task_btn”
android:layout_alignParentBottom=”true”
android:layout_alignParentEnd=”true”
android:layout_marginBottom=”20dp”
android:layout_marginEnd=”20dp”
app:elevation=”10dp”
android:contentDescription=”@string/todo” />

</RelativeLayout>

  • now, for the task we need to create an item for the task, so that creates a new layout file for our item in the layout folder (/res/layout/todo_list_item.xml)

<?xml version=”1.0" encoding=”utf-8"?>
<androidx.cardview.widget.CardView 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"
app:cardUseCompatPadding=”true”
app:cardCornerRadius=”15dp”
android:layout_margin=”3dp”
app:cardBackgroundColor=”@color/backgroundMain”
android:id=”@+id/accordian_title”>

<RelativeLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:padding=”6dp”
android:background=”@drawable/background_card_upper”>

<ImageView
android:id=”@+id/arrow”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentEnd=”true”
android:src=”@drawable/ic_arrow”
android:layout_centerVertical=”true”
android:layout_marginEnd=”20dp”
app:tint=”@color/white” />

<TextView
android:id=”@+id/task_title”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_centerVertical=”true”
android:layout_marginStart=”20dp”
android:layout_marginTop=”10dp”
android:layout_marginEnd=”60dp”
android:ellipsize=”end”
android:fontFamily=”@font/ubuntu_medium”
android:singleLine=”true”
android:text=”Go to bed”
android:textColor=”@color/white”
android:textSize=”17sp” />

</RelativeLayout>
<RelativeLayout
android:visibility=”gone”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/accordian_body”
android:padding=”5dp”
android:background=”@drawable/background_card”
android:layout_gravity=”bottom”
android:layout_marginTop=”40dp”>

<TextView
android:id=”@+id/task_description”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginLeft=”25dp”
android:layout_marginTop=”5dp”
android:layout_marginRight=”10dp”
android:fontFamily=”@font/ubuntu”
android:text=”Description: At 12AM”
android:textColor=”@color/colorPrimaryDark”
android:textSize=”13sp”/>

<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/ic_delete”
android:layout_alignParentRight=”true”
android:layout_centerVertical=”true”
android:layout_marginRight=”10dp”
android:id=”@+id/deleteBtn”
android:layout_toLeftOf=”@+id/task_description”
/>
<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/ic_baseline_edit_24"
android:layout_toLeftOf=”@+id/deleteBtn”
android:layout_marginRight=”10dp”
android:layout_centerVertical=”true”
android:id=”@+id/editBtn”
/>
<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/ic_done”
android:layout_toLeftOf=”@+id/editBtn”
android:layout_marginRight=”10dp”
android:layout_centerVertical=”true”
android:id=”@+id/doneBtn”
/>
</RelativeLayout>

</androidx.cardview.widget.CardView>

  • Here in the card view, I used two relative layout, one is for displaying the todo task title and another relative layout is for edit, delete and finish task icons that are hidden in the first place.

Todo Model

  • Now, create a model class (/package/model/TodoModel.java) for the title, description and id that also mentined in the rest API ({title: req.body.title, description: req.body.description, user: req.user.id});

package com.codewithgolap.snapshot.model;

public class TodoModel {
private String id, title, description;
public TodoModel(String id, String title, String description) {
this.id = id;
this.title = title;
this.description = description;
}

public String getId() {
return id;
}

public String getTitle() {
return title;
}

public String getDescription() {
return description;
}
}

Interface for the Click event

Now create an interface (/package/interface/RecyclerViewClickInterface.java) for the recyclerView click events (on click on the arrow button and finish the task, long click and edit button click for edit task, delete button click for delete task)

package com.codewithgolap.snapshot.Interface;

public interface RecyclerviewClickListener {
void onItemClick(int position);

void onLongItemClick(int position);

void onEditButtonClick(int position);
void onDeleteButtonClick(int position);
void onDoneButtonClick(int position);
}

Adapter class

  • Now, create an adapter class (/package/adapter/TodoListAdapter.java) to inflate our todo item list and binding our views also set our recyclerView click listener

public class TodoListAdapter extends RecyclerView.Adapter<TodoListAdapter.MyViewHolder>{

ArrayList<TodoModel> arrayList;
Context context;

final private RecyclerviewClickListener clickListener;

public TodoListAdapter(Context context, ArrayList<TodoModel> arrayList, RecyclerviewClickListener clickListener) {
this.context = context;
this.arrayList = arrayList;
this.clickListener = clickListener;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.
from(context).inflate(R.layout.todo_list_item, parent, false);
final MyViewHolder myViewHolder = new MyViewHolder(view);
int[] androidColors = view.getResources().getIntArray(R.array.
androidColors);
int randomColors = androidColors[new Random().nextInt(androidColors.length)];

myViewHolder.accordian_title.setBackgroundColor(randomColors);
myViewHolder.arrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(myViewHolder.accordian_body.getVisibility() == View.
VISIBLE) {
myViewHolder.accordian_body.setVisibility(View.
GONE);
} else {
myViewHolder.accordian_body.setVisibility(View.
VISIBLE);
}
}
});
return myViewHolder;
}

@Override
public void onBindViewHolder(@NonNull TodoListAdapter.MyViewHolder holder, int position) {
final String title = arrayList.get(position).getTitle();
final String description = arrayList.get(position).getDescription();
final String id = arrayList.get(position).getId();

holder.titleTv.setText(title);
if(!description.equals(“”)) {
holder.descriptionTv.setText(description);
}
}

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

public class MyViewHolder extends RecyclerView.ViewHolder {

CardView accordian_title;
TextView titleTv, descriptionTv;
RelativeLayout accordian_body;
ImageView arrow, editBtn, deleteBtn, doneBtn;

public MyViewHolder(@NonNull View itemView) {
super(itemView);

titleTv = (TextView) itemView.findViewById(R.id.task_title);
descriptionTv = (TextView) itemView.findViewById(R.id.
task_description);
accordian_title = (CardView) itemView.findViewById(R.id.
accordian_title);
accordian_body = (RelativeLayout) itemView.findViewById(R.id.
accordian_body);
arrow = (ImageView) itemView.findViewById(R.id.
arrow);
editBtn = (ImageView) itemView.findViewById(R.id.
editBtn);
deleteBtn = (ImageView) itemView.findViewById(R.id.
deleteBtn);
doneBtn = (ImageView) itemView.findViewById(R.id.
doneBtn);

itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition());
}
});

itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
clickListener.onLongItemClick(getAdapterPosition());
return true;
}
});

editBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickListener.onEditButtonClick(getAdapterPosition());
}
});

deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickListener.onDeleteButtonClick(getAdapterPosition());
}
});

doneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickListener.onDoneButtonClick(getAdapterPosition());
}
});
}
}
}

Add task functionality

  • Now in the home fragment java file add out functionality for adding a task.
  • First, create views and implement our click listener interface.

public class HomeFragment extends Fragment implements RecyclerviewClickListener {

SharedPreferenceClass sharedPreferenceClass;
String token;
FloatingActionButton floatingActionButton;
TodoListAdapter todoListAdapter;
RecyclerView recyclerView;
TextView emptyTv, emptyTv2;
ImageView emptyIv;
ProgressBar progressBar;
ArrayList<TodoModel> arrayList;

public HomeFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
sharedPreferenceClass = new SharedPreferenceClass(getContext());
token = sharedPreferenceClass.getValue_string(“token”);

floatingActionButton = view.findViewById(R.id.add_task_btn);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
recyclerView = view.findViewById(R.id.
recyclerView);
emptyTv = view.findViewById(R.id.
empty_text);
emptyTv2 = view.findViewById(R.id.
empty_text2);
emptyIv = view.findViewById(R.id.
empty_image);
progressBar = view.findViewById(R.id.
progressBar);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);

return view;
}

@Override
public void onItemClick(int position) {
}

@Override
public void onLongItemClick(int position) {

}

@Override
public void onEditButtonClick(int position) {
}

@Override
public void onDeleteButtonClick(int position) {
}

@Override
public void onDoneButtonClick(int position) {
}
}

  • next, create a dialog to add task function when we clicked on the floating action button

public class HomeFragment extends Fragment implements RecyclerviewClickListener {

SharedPreferenceClass sharedPreferenceClass;
String token;
FloatingActionButton floatingActionButton;
TodoListAdapter todoListAdapter;
RecyclerView recyclerView;
TextView emptyTv, emptyTv2;
ImageView emptyIv;
ProgressBar progressBar;
ArrayList<TodoModel> arrayList;

public HomeFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);

sharedPreferenceClass = new SharedPreferenceClass(getContext());
token = sharedPreferenceClass.getValue_string(“token”);

floatingActionButton = view.findViewById(R.id.add_task_btn);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAlertDialog();
}
});
recyclerView = view.findViewById(R.id.
recyclerView);
emptyTv = view.findViewById(R.id.
empty_text);
emptyTv2 = view.findViewById(R.id.
empty_text2);
emptyIv = view.findViewById(R.id.
empty_image);
progressBar = view.findViewById(R.id.
progressBar);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);

return view;
}

//show create task dialog
public void showAlertDialog() {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.
custom_dialog_layout, null);
final EditText title_field = alertLayout.findViewById(R.id.
title_edittext);
final EditText description_field = alertLayout.findViewById(R.id.
description_edittext);

final AlertDialog dialog = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setView(alertLayout)
.setTitle(“Add Task”)
.setPositiveButton(“Add”,null)
.setNegativeButton(“Cancel”, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.
BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title = title_field.getText().toString();
String description = description_field.getText().toString();
if(!TextUtils.
isEmpty(title)) {
addTask(title, description);
dialog.dismiss();

} else {
Toast.
makeText(getActivity(), “You need one title.”, Toast.LENGTH_SHORT).show();
}
}
});
}
});
dialog.show();
}

@Override
public void onItemClick(int position) {
}

@Override
public void onLongItemClick(int position) {
}

@Override
public void onEditButtonClick(int position) {
}

@Override
public void onDeleteButtonClick(int position) {
}

@Override
public void onDoneButtonClick(int position) {
}
}

  • now create a function to add the task using the rest API, also it will store the task in the MongoDB database.

public class HomeFragment extends Fragment implements RecyclerviewClickListener {

SharedPreferenceClass sharedPreferenceClass;
String token;
FloatingActionButton floatingActionButton;
TodoListAdapter todoListAdapter;
RecyclerView recyclerView;
TextView emptyTv, emptyTv2;
ImageView emptyIv;
ProgressBar progressBar;
ArrayList<TodoModel> arrayList;

public HomeFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);

sharedPreferenceClass = new SharedPreferenceClass(getContext());
token = sharedPreferenceClass.getValue_string(“token”);

floatingActionButton = view.findViewById(R.id.add_task_btn);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAlertDialog();
}
});
recyclerView = view.findViewById(R.id.
recyclerView);
emptyTv = view.findViewById(R.id.
empty_text);
emptyTv2 = view.findViewById(R.id.
empty_text2);
emptyIv = view.findViewById(R.id.
empty_image);
progressBar = view.findViewById(R.id.
progressBar);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);

return view;
}

//show create task dialog
public void showAlertDialog() {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.
custom_dialog_layout, null);
final EditText title_field = alertLayout.findViewById(R.id.
title_edittext);
final EditText description_field = alertLayout.findViewById(R.id.
description_edittext);

final AlertDialog dialog = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setView(alertLayout)
.setTitle(“Add Task”)
.setPositiveButton(“Add”,null)
.setNegativeButton(“Cancel”, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.
BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title = title_field.getText().toString();
String description = description_field.getText().toString();
if(!TextUtils.
isEmpty(title)) {
addTask(title, description);
dialog.dismiss();

} else {
Toast.
makeText(getActivity(), “You need one title.”, Toast.LENGTH_SHORT).show();
}
}
});
}
});
dialog.show();
}

// Add Todo Task Method

private void addTask(String title, String description) {

String url = “https://snapshotproject.herokuapp.com/api/snapshot";

HashMap<String, String> body = new HashMap<>();
body.put(“title”, title);
body.put(“description”, description);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(body), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.getBoolean(“success”)) {
Toast.
makeText(getActivity(), “Great!! Your task added successfully”, Toast.LENGTH_SHORT).show();
getTask();
}

} catch (JSONException e) {
e.printStackTrace();

}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

NetworkResponse response = error.networkResponse;
if(error instanceof ServerError && response != null) {
try {
String res = new String(response.data, HttpHeaderParser.
parseCharset(response.headers, “utf-8”));
JSONObject obj = new JSONObject(res);
Toast.
makeText(getActivity(), obj.getString(“msg”), Toast.LENGTH_SHORT).show();

} catch (JSONException | UnsupportedEncodingException je) {
je.printStackTrace();
}

}
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put(“Content-Type”, “application/json”);
headers.put(“Authorization”, token);
return headers;
}
};

// set retry policy
int socketTime = 3000;
RetryPolicy policy = new DefaultRetryPolicy(socketTime,
DefaultRetryPolicy.
DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);

// request add
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonObjectRequest);
}

@Override
public void onItemClick(int position) {
}

@Override
public void onLongItemClick(int position) {
}

@Override
public void onEditButtonClick(int position) {
}

@Override
public void onDeleteButtonClick(int position) {
}

@Override
public void onDoneButtonClick(int position) {
}
}

  • now, create a function for get the task from API and also initialize it in the onCreateView()

public class HomeFragment extends Fragment implements RecyclerviewClickListener {

SharedPreferenceClass sharedPreferenceClass;
String token;
FloatingActionButton floatingActionButton;
TodoListAdapter todoListAdapter;
RecyclerView recyclerView;
TextView emptyTv, emptyTv2;
ImageView emptyIv;
ProgressBar progressBar;
ArrayList<TodoModel> arrayList;

public HomeFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
sharedPreferenceClass = new SharedPreferenceClass(getContext());
token = sharedPreferenceClass.getValue_string(“token”);
floatingActionButton = view.findViewById(R.id.
add_task_btn);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAlertDialog();
}
});

recyclerView = view.findViewById(R.id.recyclerView);
emptyTv = view.findViewById(R.id.
empty_text);
emptyTv2 = view.findViewById(R.id.
empty_text2);
emptyIv = view.findViewById(R.id.
empty_image);
progressBar = view.findViewById(R.id.
progressBar);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);

getTask();
return view;
}

//get task from API
public void getTask() {
arrayList = new ArrayList<>();
progressBar.setVisibility(View.
VISIBLE);

String url = “https://snapshotproject.herokuapp.com/api/snapshot”;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.
GET,
url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.getBoolean("success")) {
// Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
JSONArray jsonArray = response.getJSONArray(“snapshots”);
if (jsonArray.length() == 0){
emptyTv.setVisibility(View.
VISIBLE);
emptyTv2.setVisibility(View.
VISIBLE);
emptyIv.setVisibility(View.
VISIBLE);
}else {
emptyTv.setVisibility(View.
GONE);
emptyTv2.setVisibility(View.
GONE);
emptyIv.setVisibility(View.
GONE);
for(int i = 0; i < jsonArray.length(); i ++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
TodoModel todoModel = new TodoModel(
jsonObject.getString(“_id”),
jsonObject.getString(“title”),
jsonObject.getString(“description”)
);
arrayList.add(todoModel);
}
todoListAdapter = new TodoListAdapter(getActivity(), arrayList, HomeFragment.this);
recyclerView.setAdapter(todoListAdapter);
}
}
progressBar.setVisibility(View.
GONE);
} catch (JSONException e) {
e.printStackTrace();
progressBar.setVisibility(View.
GONE);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
if (error == null || error.networkResponse == null){
return;
}
String body;
// final String statusCode = String.valueOf(error.networkResponse.statusCode);
try {
body = new String(error.networkResponse.data, “UTF-8”);
JSONObject errorObject = new JSONObject(body);
if (errorObject.getString(“msg”).equals(“Token not valid”)){
sharedPreferenceClass.clear();
startActivity(new Intent(getActivity(), LoginActivity.class));
Toast.
makeText(getActivity(), “Session Expired”, Toast.LENGTH_SHORT).show();
}
Toast.
makeText(getActivity(), errorObject.getString(“msg”), Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException | JSONException e){
//exception
}
progressBar.setVisibility(View.
GONE);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put(“Content-Type”, “application/json”);
headers.put(“Authorization”, token);
return headers;
}
};
// set retry policy
int socketTime = 3000;
RetryPolicy policy = new DefaultRetryPolicy(socketTime,
DefaultRetryPolicy.
DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
// request add
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonObjectRequest);
}

//show create task dialog
public void showAlertDialog() {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.
custom_dialog_layout, null);
final EditText title_field = alertLayout.findViewById(R.id.
title_edittext);
final EditText description_field = alertLayout.findViewById(R.id.
description_edittext);
final AlertDialog dialog = new AlertDialog.Builder(getActivity(), R.style.
AlertDialogTheme)
.setView(alertLayout)
.setTitle(“Add Task”)
.setPositiveButton(“Add”,null)
.setNegativeButton(“Cancel”, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.
BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title = title_field.getText().toString();
String description = description_field.getText().toString();
if(!TextUtils.
isEmpty(title)) {
addTask(title, description);
dialog.dismiss();
} else {
Toast.
makeText(getActivity(), “You need one title.”, Toast.LENGTH_SHORT).show();
}
}
});
}
});
dialog.show();
}
@Override
public void onItemClick(int position) {
}

@Override
public void onLongItemClick(int position) {
}

@Override
public void onEditButtonClick(int position) {
}

@Override
public void onDeleteButtonClick(int position) {
}

@Override
public void onDoneButtonClick(int position) {
}
}

In MongoDB

Node JS REST API code CLICK HERE

In the next tutorial, we will edit and delete tasks using Node JS REST API.
Stay tuned for the next parts.

Hi everyone, myself Golap an Android app developer with UI/UX designer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store