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:
Queryquery= memoryRef.orderByChild("name").equalTo("party");
query.addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(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:
DatabaseReferencemDatabase= FirebaseDatabase.getInstance().getReference("memories");
ValueEventListenermemListener=newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
memoryList = newArrayList<>();
Memory memory;
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
intcost= (int) userSnapshot.child("cost").getValue();
Stringname= (String) userSnapshot.child("name").getValue();
//Get other fields hereif (name.matches("party")) {
memory = newMemory(name , cost);
memoryList.add(memory);
}
}
}
@OverridepublicvoidonCancelled(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?"