简体   繁体   中英

How to remove item from firebase list

I use firebase database and recycler view. I add a list of items to firebase using the push (); command. While using push(); , firebase creating a unique id for each added item.

Now, i want delete item on click delete button, but when i try removeValue(); function to my DB ref, it delete the all repository and not just the item.

That what i have now:

Fragment that read data from 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

@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;

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. You can get id and save it in ArrayList like

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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