Edit and delete a task in todo list app| Todo Android app using Node JS and REST API | Part 6

In this series of todo app using rest API, today we will discuss how to edit and delete a task using Node JS Rest API in android.

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)

Part 5 (CLICK HERE)

Overview

API (Node Js)

  • To edit or update the task create an API for updating the task.

//desc update tasks

//method PUT

router.put(‘/:id’, async (req, res, next) => {

try {

let snapShot = await Snapshot.findById(req.params.id);

if(!snapShot){

return res.status(400).json({

success: false,

msg: ‘Task snapshot not exists!’

});

}

snapShot = await Snapshot.findByIdAndUpdate(req.params.id, req.body, {

new: true,

runValidators: true

});

if(!snapShot){

return res.status(400).json({

success: false,

msg: ‘Something went wrong!’

});

}

res.status(200).json({

success: true,

snapshot: snapShot,

msg: ‘Successfully updated..’

});

} catch (error) {

next(error);

}

})

  • Same way create an API for the delete task.

//desc delete tasks

//method DELETE

router.delete(‘/:id’, async(req, res, next) => {

try {

let snapShot = await Snapshot.findById(req.params.id);

if(!snapShot){

return res.status(400).json({

success: false,

msg: ‘Task snapshot not exists!’

});

}

snapShot = await Snapshot.findByIdAndDelete(req.params.id);

res.status(200).json({

success: true,

msg: ‘Successfully deleted..’

});

} catch (error) {

next(error);

}

})

Set the click event

  • First set the click events.
  • that means when we clicked on the edit button or long-press on the item an alert dialog will appears. So first set the click event then create an alert dialog for the editing.

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) {
…………………………………………

getTask();
return view;
}

//get task from API
public void getTask() {………………………….}

//show create task dialog
public void showAlertDialog() {……………………}

//show edit task dialog
public void showUpdateDialog(final String id, String title, String description){
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);

title_field.setText(title);
description_field.setText(description);

final AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setView(alertLayout)
.setTitle(“Update Task”)
.setPositiveButton(“Update”, null)
.setNegativeButton(“Cancel”, null)
.create();

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button button = ((AlertDialog)alertDialog).getButton(AlertDialog.
BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = title_field.getText().toString();
String description = description_field.getText().toString();

updateTask(id, title, description);
alertDialog.dismiss();
}
});
}
});

alertDialog.show();
}

// Add Todo Task Method
private void addTask(String title, String description) {}

@Override
public void onItemClick(int position) {
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

@Override
public void onLongItemClick(int position) {
showUpdateDialog(arrayList.get(position).getId(), arrayList.get(position).getTitle(), arrayList.get(position).getDescription());
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();

}

@Override
public void onEditButtonClick(int position) {
showUpdateDialog(arrayList.get(position).getId(), arrayList.get(position).getTitle(), arrayList.get(position).getDescription());
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

@Override
public void onDeleteButtonClick(int position) {
}

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

  • Same way when we clicked on the delete button, an alert dialog will appear for deleting the task.

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) {

…………………………………………………………..see the previous tutorial of add task………………………………

getTask();
return view;
}

//get task from API
public void getTask() {………………… }

//show create task dialog
public void showAlertDialog() {………………….}

//show edit task dialog
public void showUpdateDialog(final String id, String title, String description){…………………. }

//show delete task dialog
public void showDeleteDialog(final String id, final int position){

final AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setTitle(“Are you want to delete the task ?”)
.setPositiveButton(“Yes”, null)
.setNegativeButton(“No”, null)
.create();

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button button = ((AlertDialog)alertDialog).getButton(AlertDialog.
BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteTask(id, position);
alertDialog.dismiss();
}
});
}
});

alertDialog.show();
}

// Add Todo Task Method
private void addTask(String title, String description) {…………………..}

@Override
public void onItemClick(int position) {
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

@Override
public void onLongItemClick(int position) {
showUpdateDialog(arrayList.get(position).getId(), arrayList.get(position).getTitle(), arrayList.get(position).getDescription());
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();

}

@Override
public void onEditButtonClick(int position) {
showUpdateDialog(arrayList.get(position).getId(), arrayList.get(position).getTitle(), arrayList.get(position).getDescription());
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

@Override
public void onDeleteButtonClick(int position) {
showDeleteDialog(arrayList.get(position).getId(), position);
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

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

Set the API

  • Now set the editing and deleting API with the task.

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) {
…………………………………….

getTask();
return view;
}

//get task from API
public void getTask() {……………}

//show create task dialog
public void showAlertDialog() {……………}

// Add Todo Task Method
private void addTask(String title, String description) {………}

//show edit task dialog
public void showUpdateDialog(final String id, String title, String description){
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);

title_field.setText(title);
description_field.setText(description);

final AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setView(alertLayout)
.setTitle(“Update Task”)
.setPositiveButton(“Update”, null)
.setNegativeButton(“Cancel”, null)
.create();

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button button = ((AlertDialog)alertDialog).getButton(AlertDialog.
BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = title_field.getText().toString();
String description = description_field.getText().toString();

updateTask(id, title, description);
alertDialog.dismiss();
}
});
}
});

alertDialog.show();
}

//show delete task dialog
public void showDeleteDialog(final String id, final int position){

final AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setTitle(“Are you want to delete the task ?”)
.setPositiveButton(“Yes”, null)
.setNegativeButton(“No”, null)
.create();

alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button button = ((AlertDialog)alertDialog).getButton(AlertDialog.
BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteTask(id, position);
alertDialog.dismiss();
}
});
}
});

alertDialog.show();
}

//delete task
private void deleteTask(final String id, final int position){
String url = “https://snapshotproject.herokuapp.com/api/snapshot/"+id;

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.DELETE, url, null
, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if (response.getBoolean(“success”)){
Toast.
makeText(getActivity(), response.getString(“msg”), Toast.LENGTH_SHORT).show();
arrayList.remove(position);
todoListAdapter.notifyItemRemoved(position);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.
makeText(getActivity(), error.toString(), Toast.LENGTH_SHORT).show();
}
});

jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

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

//update task
private void updateTask(String id, String title, String description) {
String url = “https://snapshotproject.herokuapp.com/api/snapshot/"+id;
HashMap<String, String> body = new HashMap<>();
body.put(“title”, title);
body.put(“description”, description);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, new JSONObject(body),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.getBoolean(“success”)) {
getTask();
Toast.
makeText(getActivity(), response.getString(“msg”), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.
makeText(getActivity(), error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(“Content-Type”, “application/json”);
params.put(“Authorization”, token);
return params;
}
};

jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

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

@Override
public void onItemClick(int position) {
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

@Override
public void onLongItemClick(int position) {
showUpdateDialog(arrayList.get(position).getId(), arrayList.get(position).getTitle(), arrayList.get(position).getDescription());
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();

}

@Override
public void onEditButtonClick(int position) {
showUpdateDialog(arrayList.get(position).getId(), arrayList.get(position).getTitle(), arrayList.get(position).getDescription());
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

@Override
public void onDeleteButtonClick(int position) {
showDeleteDialog(arrayList.get(position).getId(), position);
Toast.
makeText(getActivity(), “Position “+ position, Toast.LENGTH_SHORT).show();
}

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

Node JS REST API code CLICK HERE

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

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