Implement Delete Messages Functionality in Social Media Android App
Last Updated :
23 May, 2024
This is the Part 15 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article:
- We are going to delete the message in the ChatActivity.
- We are going to delete text and image messages. When we click on a text then an AlertBox will come.
- There will be two options to either delete that message or cancel the event. After Click on delete message will be deleted from both sides.
Step By Step Implementation
Step 1: Working with the AdapterChat.java file
We can delete a message only if we are the sender of the message. There are two methods to delete the message. You can use any one of them. In one, we have removed the value using datasnapshot and in another, we have updated the message as "This Message Was Deleted" as we see in WhatsApp.
if(dataSnapshot1.child("sender").getValue().equals(myuid)) {
// any two of below can be used
dataSnapshot1.getRef().removeValue();
// <----------------------------------->
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This Message Was Deleted");
dataSnapshot1.getRef().updateChildren(hashMap);
Toast.makeText(context,"Message Deleted.....",Toast.LENGTH_LONG).show();
}
Below is the code for the AdapterChat.java file.
Java
package com.example.socialmediaapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import de.hdodenhof.circleimageview.CircleImageView;
public class AdapterChat extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterChat.Myholder> {
private static final int MSG_TYPE_LEFT = 0;
private static final int MSG_TYPR_RIGHT = 1;
Context context;
List<ModelChat> list;
String imageurl;
FirebaseUser firebaseUser;
public AdapterChat(Context context, List<ModelChat> list, String imageurl) {
this.context = context;
this.list = list;
this.imageurl = imageurl;
}
@NonNull
@Override
public Myholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_LEFT) {
View view = LayoutInflater.from(context).inflate(R.layout.row_chat_left, parent, false);
return new Myholder(view);
} else {
View view = LayoutInflater.from(context).inflate(R.layout.row_chat_right, parent, false);
return new Myholder(view);
}
}
@Override
public void onBindViewHolder(@NonNull Myholder holder, final int position) {
String message = list.get(position).getMessage();
String timeStamp = list.get(position).getTimestamp();
String type = list.get(position).getType();
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(Long.parseLong(timeStamp));
String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString();
holder.message.setText(message);
holder.time.setText(timedate);
try {
Glide.with(context).load(imageurl).into(holder.image);
} catch (Exception e) {
}
if (type.equals("text")) {
holder.message.setVisibility(View.VISIBLE);
holder.mimage.setVisibility(View.GONE);
holder.message.setText(message);
} else {
holder.message.setVisibility(View.GONE);
holder.mimage.setVisibility(View.VISIBLE);
Glide.with(context).load(message).into(holder.mimage);
}
holder.msglayput.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete Message");
builder.setMessage("Are You Sure To Delete This Message");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteMsg(position);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
}
private void deleteMsg(int position) {
final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String msgtimestmp = list.get(position).getTimestamp();
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child("Chats");
Query query = dbref.orderByChild("timestamp").equalTo(msgtimestmp);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
if (dataSnapshot1.child("sender").getValue().equals(myuid)) {
// any two of below can be used
dataSnapshot1.getRef().removeValue();
/* HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This Message Was Deleted");
dataSnapshot1.getRef().updateChildren(hashMap);
Toast.makeText(context,"Message Deleted.....",Toast.LENGTH_LONG).show();
*/
} else {
Toast.makeText(context, "you can delete only your msg....", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public int getItemCount() {
return list.size();
}
@Override
public int getItemViewType(int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (list.get(position).getSender().equals(firebaseUser.getUid())) {
return MSG_TYPR_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
class Myholder extends RecyclerView.ViewHolder {
CircleImageView image;
ImageView mimage;
TextView message, time, isSee;
LinearLayout msglayput;
public Myholder(@NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.profilec);
message = itemView.findViewById(R.id.msgc);
time = itemView.findViewById(R.id.timetv);
isSee = itemView.findViewById(R.id.isSeen);
msglayput = itemView.findViewById(R.id.msglayout);
mimage = itemView.findViewById(R.id.images);
}
}
}
Output:Â
Note: Please Add drawable items before running the Application
Below is the file structure after performing these operations:

Â
Similar Reads
Implement Delete a Blog Post Functionality in Social Media Android App This is the Part 13 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to delete the Blog written by the user.Blogs can only be deleted by the owner of blogs. In the top right of the blog, a button is there.
5 min read
How to Implement Chat Functionality in Social Media Android App? This is the Part 14 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Create a Layout for chat & Send Messages in Chat.A user can send either a Message or an Image.A user can send an image either usi
15+ min read
Implementing Edit Profile Data Functionality in Social Media Android App This is the Part 3 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to edit our profile data like changing name, changing the password of the user, and changing profile pic.Changing password is a very impo
10 min read
Implement Retrieve Profile Data Functionality in Social Media Android App This is the Part 4 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to retrieve data of users From Firebase.This is a simple fragment in which we will retrieve data of users like name, email, and profile p
3 min read
Implement Like a Blog Post Functionality in Social Media Android App This is the Part 10 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Like a Blog. We are implementing this feature using two images one like button with white background and another like button with blu
5 min read
Implement Comment on a Particular Blog Functionality in Social Media Android App This is the Part 11 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to comment on the blog.Here we are going to write a comment, and then we will be showing the comments and will be updating the comment c
9 min read
How to Implement Search for a Registered User Functionality in Social Media Android App? This is the Part 9 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Search For a user on the Users Page.If there are few people registered in our app then it is easy to search for a person.But what happ
3 min read
Implement Splash Screen and Authentication in Social Media Android App This is the Part 1 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: Creating a Splash ScreenAuthentication Part:Registration, andLoginStep By Step ImplementationStep 1: Create a New Project To create a new project in A
10 min read
Implementing Search for a Specific Blog On Home Page and Logout Functionality in Social Media Android App This is the Part 7 of "Build a Social Media App in Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Search For a Blog on Home Page.If there are few blogs in our app then it is easy to search for a blog manually. But what happens when
4 min read