Skip to content Skip to sidebar Skip to footer

Android Firebase: How To Change Objects With Specific Field Value?

Firebase database node 'memories/' contains objects of type Memory{String name; int cost; ...} I need to get objects with specific 'name' field (for example 'party') and delete th

Solution 1:

You could use a query:

Query query = memoryRef.orderByChild("name").equalTo("party");
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            for (DataSnapshot child : dataSnapshot.getChildren()) {
                //to update:
                memoryRef.child(child.getKey()).child("cost").setValue(100);
                //delete
                memoryRef.child(child.getKey()).removeValue();
            }
        }
    });

Note: Do remember to set indexOn rule on "name" for Memory

Your rule should looks like this:

{
  "rules": {
    ...
    "memories": {
      ".indexOn": "name"
    }
  }
}

Solution 2:

There could be more ideal approaches, but this is what works for me:

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("memories");
    ValueEventListener memListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            memoryList = new ArrayList<>();
            Memory memory;

            for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {

                int cost = (int) userSnapshot.child("cost").getValue();
                String name = (String) userSnapshot.child("name").getValue();
                //Get other fields here

                if (name.matches("party")) {
                    memory = new Memory(name , cost);
                    memoryList.add(memory);
                }

            }


        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    mDatabase.addValueEventListener(memListener);

PS: I'm just adding it to an array here... You could change it as you require


Post a Comment for "Android Firebase: How To Change Objects With Specific Field Value?"