Jared
Jared

Reputation: 2217

Android Firebase Remove An Item From A List

I am trying to remove an item from a list in the database. It was added with .push().

Here is an example:

enter image description here

For instance, I would like to remove "8mtuj28..." from the list (and I have the key btw).

Here is an example of some code I expected to work:

//remove poll from author's list of polls
authorRef.child(getString(R.string.my_polls_ref)).child(pollIds.get(currentPoll)).removeValue();

Any help is appreciated!

EDIT:

I have realized that I needed to use an integer for the key instead of a string. I was completely ignoring the numbers in front of the poll keys. I think I will change all of this to a Map instead of a list.

Upvotes: 1

Views: 5479

Answers (5)

Junia Montana
Junia Montana

Reputation: 623

If you are viewing items from Firebase database onto the recyclerview/list and trying to remove each item per click or swipe to delete, this solution is for you: First, lets assume we a List listOfApples = new ArrayList<>(); and it has some data in it.

public void removeItems(int position, DatabaseReference ref){
String appleName = "";
double applePrice = 0.0;
for(int i = 0; i < listOfApples.size(); i++){
if(i == position){
appleName = listOfApples.get(i).getAppleName();
applePrice = listOfApples.get(i).getApplePrice();
listOfApples.remove(position);
notifyDataChanged();
notifyItemRangeChanged(position, getItemCount);
}
}
final String finalAppleName = appleName;
final double finalApplePrice = applePrice;
ValueEventListener removeListener = new ValueEventListener(){ 
@Override
public void onDataChanged(@NonNull DataSnapShot dataSnapshot(){
for(DataSnapshot snapShot: dataSnapShot().getChildren()){
if(snapShot != null){
Apple apple = snapShot.getValue(Apple.class);
if(apple != null){
if(apple.getAppleName().equals(finalAppleName) && apple.getApplePrice() == finalApplePrice){
if(ref != null && snapShot.getKey() != null){
ref.child(snapShot.getKey()).removeValue(new DatabaseReference.CompletionListener(){
@Override
 public void onComplete(@Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference) {
// show a message or do whatever you feel like
});
      }
     }
    }
   }
  }
}
@Override
 public void onCancelled(@NonNull DatabaseError databaseError) {

        }
};
ref.addValueEventListener(removeListener);
}

Thats all it. Now, here's one caveat with this solution that I want to point out, we are deleting the item from the recyclerview first and then we are deleting it from the firebase database. What if user gets disconnected from network while removing an item? Some of you might be okay with with that because you can just show a message to your user that failed to remove because of some issues.For those who are not okay with it, you can remove that item in onComplete(..) method, notify the adapter and refresh/recreate the activity.

Upvotes: 0

Dave Rincon
Dave Rincon

Reputation: 358

that is my solution but i have a jsobject in my list

    String value = "valor";
    Sting key = "key";                                                          
    Query query = mDatabase.child(path).child(mFirebaseAuth.getUid());
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                for(DataSnapshot du : dataSnapshot.getChildren()){
                    if(value.contentEquals(du.child(key).getValue().toString())){
                        mDatabase.child(path).child(mFirebaseAuth.getUid()).child(du.getKey()).removeValue();
                    }
                }
            }
        }

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

        }
    });

Upvotes: 1

Matthew Ellison
Matthew Ellison

Reputation: 176

Not sure if got the answer you need but this should remove an item from the list. You ultimately just have to drill down to the node that you want to get removed.

firebase.database().ref('uft0jep4knqlnum...').remove();

From "Delete data" Section at

https://firebase.google.com/docs/database/web/read-and-write Remove Item from Firebase database

Upvotes: 0

shiami
shiami

Reputation: 7264

for (DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
    final String key = childSnapShot.getKey();
}

Upvotes: 0

Rajesh Satvara
Rajesh Satvara

Reputation: 3954

// from key you can get 0,1,2,3,4,... value of firebase db.

if you know that value like here for your key is 1 for your 8mtu....

ref.child("myPolls").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        // you can pass here that value instead of **1**
                        ref.child("myPolls).child("1").setValue(null);
                    }
                    @Override
                    public void onCancelled(FirebaseError firebaseError) {
                    }
                });

Upvotes: 0

Related Questions