我正在使用Firebase编写一个简单的聊天应用程序。我的数据库看起来像这样
现在,我想将变量“counter”(+1)增加到具有一个groupId的所有对象(例如:groupId =“eee1111111111111”)
我只知道只有一个DatabaseReference的事务,如
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
}
});`
答案 0 :(得分:4)
您可以查询所有groupId等于“eee1111111111111”的孩子 然后循环所有这个孩子并更新计数
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());
}
});
答案 1 :(得分:1)
感谢@Phan van Linh的帮助。我的代码找到了一个问题。我使用addListenerForSingleValueEvent方法而不是addValueEventListener方法(这使得循环永远在更新数据库中)。现在我的代码如:
private void updateRecents(String groupId){
final DatabaseReference mRecent = myDataRef.child(Consts.CHILD_RECENT);
mRecent.orderByChild("groupId").equalTo(groupID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren()){
DatabaseReference mCount = mRecent.child(child.getKey());
UpdateCounterWithTransaction(mCount);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void UpdateCounterWithTransaction(DatabaseReference _mCount){
_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) {
}
});
}