提问者:小点点

Android Firebase实时数据库删除id由Firebase命名的子节点


但是我不想硬编码最后一个孩子的id。这里我想在单击时获取“yaada”下的特定节点的id,然后将其删除。但是我不想硬编码最后一个孩子的id。

最终的数据库引用数据库=FirebaseDatabase. getInstance().get引用("照片").child(photo_id).child("yaada").child("-M7YsqlH_EZdrbFzdg8y");数据库移除值();

检查持有者.删除………

这是我的数据库

这是我在FirebaseMethod. class中添加评论的地方

public void addNewComment(final String node, final String mediaId, final String comment){

final String commentId = myRef.push().getKey();
final String dateAdded = new SimpleDateFormat("dd-MM-yyyy ",Locale.getDefault()).format(Calendar.getInstance().getTime());
Query query = myRef.child(mActivity.getString(R.string.user_account_settings_node)).child(userID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        String userName = Objects.requireNonNull(dataSnapshot.child(mActivity.getString(R.string.usernameField)).getValue()).toString();
        String profileImage = Objects.requireNonNull(dataSnapshot.child(mActivity.getString(R.string.profilePhotoField)).getValue()).toString();

        Comment comment_model = new Comment(comment, dateAdded, userName, profileImage, 0);
        myRef.child(node).child(mediaId).child(mActivity.getString(R.string.fieldComments))
                .child(Objects.requireNonNull(commentId)).setValue(comment_model);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});

这是我的CommentListAdapter类;

   public class CommentListAdapter extends ArrayAdapter<Comment> {

        private Activity mContext;
        private int layoutResource;
        private long limit=20;
        private UtilityInterface utilityInterface;
        private FirebaseAuth mAuth;


        CommentListAdapter(@NonNull Activity context, int resource, ArrayList<Comment> comments) {
            super(context,resource,comments);
            mContext = context;
            layoutResource = resource;
            utilityInterface = (UtilityInterface)mContext;
        }

        private static class ViewHolder{

            ImageView profileImage;
            TextView comment;
            //TextView commentLike;
            TextView dateAdded;
            ImageView addLike;
            TextView commentReply;
        }




        @NonNull
        @Override
        public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

            final ViewHolder holder;
            mAuth = FirebaseAuth.getInstance();

            SharedPreferences prefs = mContext.getSharedPreferences("pass_user_id", MODE_PRIVATE);
            final String user_id = prefs.getString("user_id", "");
            final String photo_id = prefs.getString("photo_id", "");


            if(convertView==null) {
                convertView = LayoutInflater.from(mContext).inflate(layoutResource, parent, false);
                holder = new ViewHolder();

                holder.profileImage = convertView.findViewById(R.id.comment_profile);
                holder.comment = convertView.findViewById(R.id.comment);
                //holder.commentLike = convertView.findViewById(R.id.commentLike);
                holder.dateAdded = convertView.findViewById(R.id.date_added);
                holder.addLike = convertView.findViewById(R.id.comment_heart);
                holder.commentReply = convertView.findViewById(R.id.commentReply);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder)convertView.getTag();
            }


            final Comment commentData = getItem(position);


            //Setting profile image
            GlideImageLoader.loadImageWithOutTransition(mContext, Objects.requireNonNull(commentData).getProfile_image(),holder.profileImage);
            //Setting userName and comment
            final String userName = Objects.requireNonNull(commentData).getUser_name();
            SpannableStringBuilder str = new SpannableStringBuilder(userName+" "+commentData.getComment());
            str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), 0, userName.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.comment.setText(str);
            //Setting date
            holder.dateAdded.setText(commentData.getDate_added());

            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    //                if (user_id.equals(mAuth.getCurrentUser().getUid().toString())){
    //

                    final Intent mediaIntent = mContext.getIntent();
                    String photo_id = mediaIntent.getStringExtra("photo_id");
                    String user_id = mediaIntent.getStringExtra("user_id");

                    FirebaseDatabase fb_db_instance = FirebaseDatabase.getInstance();

                    final DatabaseReference database = (DatabaseReference) FirebaseDatabase.getInstance().getReference("photos").child(photo_id).child(mContext.getString(R.string.fieldComment));
    //                DatabaseReference db_ref_Main = fb_db_instance.getReference(database.push().getKey());
                    database.removeValue();  

                }

            });



            return  convertView;
        }




    }

共1个答案

匿名用户

我建议您在yaada下为您的子节点分配唯一名称,然后您可以轻松获取该节点的id并删除或做任何您想做的事情。以下是您的操作方法。

//Before pushing, assign a unique userId to each child node
String uniqueId= ( hash created using username and date_added);

FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference rootReference=firebaseDatabase.getReference();
DatabaseReference myRef = rootReference.child("photos").child(photo_id).child("yaada").child(uniqueId);
CommentClass newComment=new CommentClass(comment,commentLikes,date,profileImage,userName);
 myRef.setValue(newComment).addOnCompleteListener(new OnCompleteListener<Void>()    {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
           //add your onComplete logic
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
           //add your onFailure logic

        }
    });

因此,下次如果您想对该节点进行任何更改,您只需使用该节点的id。

uniqueId.removeValue();

如果您想使用Firebase提供的id,请参阅以下方法:

FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference rootReference=firebaseDatabase.getReference();
DatabaseReference myRef = rootReference.child("photos").child(photo_id).child("yaada");
CommentClass newComment=new CommentClass(comment,commentLikes,date,profileImage,userName);

String childId= myRef.push().getKey();
myRef.child(childId).setValue(newComment);