📌  相关文章
📜  在社交媒体Android应用中实现删除消息功能

📅  最后修改于: 2021-05-08 19:43:47             🧑  作者: Mango

这是15“建立一个社交媒体应用程序在Android工作室”教程中的一部分,我们将要在本文中介绍了以下功能:

  • 我们将删除ChatActivity中的消息。
  • 我们将删除文本和图像消息。当我们单击文本时,将出现一个AlertBox
  • 有两个选项可以删除该消息或取消该事件。单击删除后,消息将从两侧被删除。

分步实施

步骤1:使用AdapterChat。 Java文件

仅当我们是邮件的发件人时,我们才能删除该邮件。有两种删除消息的方法。您可以使用其中任何一个。一方面,我们使用datasnapshot删除了该值,另一方面,我们将消息更新为“此消息已删除”,如我们在WhatsApp中看到的那样。

if(dataSnapshot1.child("sender").getValue().equals(myuid)) {
// any two of below can be used
dataSnapshot1.getRef().removeValue();

// <----------------------------------->   
HashMap hashMap = new HashMap<>();
hashMap.put("message", "This Message Was Deleted");
dataSnapshot1.getRef().updateChildren(hashMap);
Toast.makeText(context,"Message Deleted.....",Toast.LENGTH_LONG).show();
}

下面是AdapterChat的代码。 Java文件。

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 {
    private static final int MSG_TYPE_LEFT = 0;
    private static final int MSG_TYPR_RIGHT = 1;
    Context context;
    List list;
    String imageurl;
    FirebaseUser firebaseUser;
  
    public AdapterChat(Context context, List 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 Messgae");
                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 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 delet 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);
        }
    }
}


输出:

对于本文中使用的所有可绘制文件,请参考以下链接: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing

下面是执行这些操作后的文件结构: