Take a look at this GIF I recorded:
This is the database of a counter app I'm making. When a user increments, count
gets added along with the count
under
users:{
UID:{
count: x
}
}
However, if you can notice in the GIF, sometimes, the upper count gets incremented but the one under users
doesn't. Here's the code I'm saving it with:
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());
}
});
}
});
None of the onFailure
methods get called. So why is this happening?
You can instead listen to the users
node to count the total count. Here's an example
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();
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With