简体   繁体   English

如何从 firebase 列表中删除项目

[英]How to remove item from firebase list

I use firebase database and recycler view.我使用 firebase 数据库和回收站视图。 I add a list of items to firebase using the push ();我使用 push () 将项目列表添加到 firebase; command.命令。 While using push();使用 push() 时; , firebase creating a unique id for each added item. , firebase 为每个添加的项目创建一个唯一的 id。

Now, i want delete item on click delete button, but when i try removeValue();现在,我想在单击删除按钮时删除项目,但是当我尝试 removeValue(); function to my DB ref, it delete the all repository and not just the item. function 到我的数据库参考,它删除所有存储库而不仅仅是项目。

That what i have now:这就是我现在所拥有的:

Fragment that read data from firebase从 firebase 读取数据的片段

users.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
                notes.clear();
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    note = dataSnapshot1.getValue(Note.class);
                    notes.add(note);
                }
                adapter = new NotesAdapter(notes, getActivity());
                RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
                RVNotesList.setLayoutManager(layoutManager);
                RVNotesList.setAdapter(adapter);
                adapter.setOnNoteClickListener(new NotesAdapter.OnNoteClickListener() {
                    @Override
                    public void onNoteClick(final int position) {
                       users.addListenerForSingleValueEvent(new ValueEventListener() {
                           @Override
                           public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                               //TODO delete pressed item.
                           }

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

                           }
                       });
                    }
                });
            }

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

            }
        });

My onClick buttons我的 onClick 按钮

@Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saveNoteBTN:
                String title = ETnoteTitle.getText().toString().trim();
                String desc = ETnoteDesc.getText().toString().trim();
                String date = ETnoteLastDate.getText().toString().trim();
                if (title.isEmpty() || desc.isEmpty() || date.isEmpty()) {
                    return;
                }
                note = new Note(title, desc, date);
                users.push().setValue(note).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d("NoteAdded", "true");
                        getFragmentManager().beginTransaction().
                                remove(getFragmentManager().findFragmentById(R.id.bottom_container)).commit();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("NoteAdded", "false");
                    }
                });
                break;
            case R.id.deleteNoteBTN:
                getFragmentManager().beginTransaction().
                        remove(getFragmentManager().findFragmentById(R.id.bottom_container)).commit();
                break;
        }
    }

Adapter package com.enjoyapp.eventmanagement.Adapters;适配器 package com.enjoyapp.eventmanagement.Adapters;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.enjoyapp.eventmanagement.Models.Note;
import com.enjoyapp.eventmanagement.R;

import java.util.ArrayList;

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NotesViewHolder> {

    private ArrayList<Note> notes;
    private Context context;
    private OnNoteClickListener onNoteClickListener;

    public NotesAdapter(ArrayList<Note> notes, Context context) {
        this.notes = notes;
        this.context = context;
    }

    public interface OnNoteClickListener {
        void onNoteClick(int position);
    }

    public void setOnNoteClickListener(OnNoteClickListener onNoteClickListener) {
        this.onNoteClickListener = onNoteClickListener;
    }

    @NonNull
    @Override
    public NotesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_list_item, parent, false);
        return new NotesAdapter.NotesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final NotesViewHolder holder, final int position) {
        final Note note = notes.get(position);
        holder.mNoteTitle.setText(notes.get(position).getmTitle());
        holder.mNoteDesc.setText(notes.get(position).getmDescription());
        String lastDayToConfirmNote = (notes.get(position).getmDay() + "/"
                + notes.get(position).getmMonth() + "/" + notes.get(position).getmYear());
        holder.mLastDay.setText(lastDayToConfirmNote);
    @Override
    public int getItemCount() {
        return notes.size();
    }

    public class NotesViewHolder extends RecyclerView.ViewHolder {

        private TextView mNoteTitle;
        private TextView mNoteDesc;
        private TextView mLastDay;
        private CardView note_card;


        public NotesViewHolder(@NonNull View itemView) {
            super(itemView);
            mNoteTitle = itemView.findViewById(R.id.note_title);
            mNoteDesc = itemView.findViewById(R.id.note_description);
            mLastDay = itemView.findViewById(R.id.note_last_date);
            note_card = itemView.findViewById(R.id.note_card);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (onNoteClickListener!=null){
                        onNoteClickListener.onNoteClick(getAdapterPosition());
                    }
                }
            });
        }
    }

    public void removeItem(ArrayList arrayList, int position) {
        arrayList.remove(arrayList.get(position));
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, arrayList.size());
    }
}

According to your code, it seems that users is your parent root and you want to delete one of the child of users.根据您的代码,用户似乎是您的父根,您想删除其中一个用户的孩子。 For that, you will need the id of that child.为此,您将需要该孩子的 id。 You can get id and save it in ArrayList like您可以获取 id 并将其保存在 ArrayList 中,例如

ArrayList<String> ids = new ArrayList
users.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
            notes.clear();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                note = dataSnapshot1.getValue(Note.class);
                notes.add(note);

                ids.add(dataSnapshot1.getKey());//saving id of each child
            }
            adapter = new NotesAdapter(notes, getActivity());
            RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
            RVNotesList.setLayoutManager(layoutManager);
            RVNotesList.setAdapter(adapter);
            adapter.setOnNoteClickListener(new NotesAdapter.OnNoteClickListener() {
                @Override
                public void onNoteClick(final int position) {
                   users.child(ids.get(position)).removeValue();
                }
            });
        }

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

        }
    });

NOTE : You have to update ids arraylist when you will update notes arraylist.注意:当您更新笔记 arraylist 时,您必须更新 ids arraylist。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM