看看我录制的这个GIF:
这是我正在制作的计数器应用程序的数据库。当用户增加时,count
会与<{p}}下的count
一起添加
users:{
UID:{
count: x
}
}
但是,如果您在GIF中注意到,有时候,上限计数会增加,但users
下的计数则不会增加。这是我用它保存的代码:
database = database.child("users").child(auth.getCurrentUser().getUid()).child("count");
final DatabaseReference finalDatabase = database;
database.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get the latest int
final int[] i = {Integer.parseInt(button.getText().toString())};
//add to the user's count with an onFailureListener
finalDatabase.setValue(i[0]++).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG,"Adding user's count failed: " + e.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//Now add to the original
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("Campaigns").child(key).child("count").setValue(i[0]++).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Error: " + e.getMessage());
}
});
}
});
没有onFailure
方法被调用。那为什么会这样呢?
答案 0 :(得分:1)
您可以听取users
节点来计算总计数。这是一个例子
private Map<String, Long> userCount = new HashMap<>();
private Long totalCount = 0L;
private void addTotalCountListener() {
FirebaseDatabase.getInstance().getReference().child("users").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
userCount.put(dataSnapshot.getKey(), user.getCount);
totalCount += user.getCount();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// subtract the total count with the previous count
totalCount -= userCount.get(dataSnapshot.getKey());
// then add the new count
User user = dataSnapshot.getValue(User.class);
userCount.put(dataSnapshot.getKey(), user.getCount);
totalCount += user.getCount();
}
});
}