Deleting row from recycler view and firebase

后端 未结 1 970
我在风中等你
我在风中等你 2020-12-12 05:21

I am trying to delete arow from firebase when swiped in the recycler view. I have managed to remove the record from the recycler view but am struggling with deleting it from

相关标签:
1条回答
  • 2020-12-12 05:51

    To delete a node from the Firebase Realtime Database you need to have a reference to its exact, complete path. You have such references when you're loading the data. For example in the onDataChange you could delete each node with:

    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
            //Booking b = dataSnapshot1.getValue(Booking.class);
            dataSnapshot1.getRef().removeValue();
        }
    }
    

    Of course that is not what you want to do, but it shows how deleting from Firebase works. You need to know the full path of the node you're trying to delete, which including the key of that child node.

    In your listener you get the value from each child node and add that to a list, that you then display in the adapter. But you're not getting the key of each child node. This means that your list/adapter only have part of the knowledge needed to delete the nodes. By the time your deleteItem function gets called with the position of the item to delete, there is no way to look up the key of that node anymore.

    So you need to keep track of both the keys and the values of the child nodes that are in your adapter. A common way to do this is by keeping two lists: one with the keys, and one with the values.

    So first you add a List<String> for the keys to your adapter:

    ArrayList<Booking> bookings;
    ArrayList<String> keys;
    

    And accept that in the adapter's constructor:

    public MyAdapterBookings(Context c , ArrayList<Booking> b, ArrayList<String> k)
    {
        context = c;
        bookings = b;
        keys = k;
    }
    

    Then you add each key in onDataChange:

    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        Log.d(TAG, "populating recyclerview");
    
        list = new ArrayList<Booking>();
        List<String> keys = new ArrayList<String>();
        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
            Booking b = dataSnapshot1.getValue(Booking.class);
            list.add(b);
            keys.add(dataSnapshot1.getKey());
        }
        adapter = new MyAdapterBookings(CustomerProfile.this, list, keys);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    

    And finally you can then look up the key for the item to delete:

    public void deleteItem(int position){
        String key = keys.get(position);
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Booking");
        ref.child(key).removeValue();
    }
    
    0 讨论(0)
提交回复
热议问题