Geo Wesley Geo Wesley - 1 month ago 28
Android Question

Update value to mutiply objects by Transaction in Firebase

I'm new to android and Firebase

I'm writting simple chat application with Firebase. My Database see like thisenter image description here like this

Now, I wana increament variable "counter" (+1) to all objects with one groupId (ex: groupId ="eee1111111111111")

I only know transaction with only one DatabaseReference like as

DatabaseReference mCount = myDataRef.child(Consts.CHILD_RECENT).child("-
KUgZ3_5nXUpsyVNTnn5");

mCount.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
FRecent f = mutableData.getValue(FRecent.class);
if (f == null) {
return Transaction.success(mutableData);
}
f.counter = f.counter + 1;
mutableData.setValue(f);
return Transaction.success(mutableData);
}

@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed


}
});`

Answer

You can query all child that have groupId equalTo "eee1111111111111".
Then you loop all this child and update the count number

DatabaseReference ref = myDataRef.child(Consts.CHILD_RECENT);
ref.orderByChild("groupId").equalTo("eee1111111111111").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // loop all result
        for (DataSnapshot child: snapshot.getChildren()) {
            // update count for child: child.getKey()
            DatabaseReference mCount = ref.child(child.getKey());

            // run your transaction here
            mCount.runTransaction(new Transaction.Handler() {
                ...
            }
        }
    } 

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
});