How To Increment Number In Firebase
I've edited the code. It works. It increment the counter in firebase. But there is 1 problem. Whenever I restart the app (after clear recent app), the increment starts over. It doe
Solution 1:
Three things require fixing:
count
in your DB is a number and will be read as aLong
. You cannot cast directly toint
. Instead you can cast to along
, or you could use two casts:int count = (int)(long) ...
- You are using the post-increment operator. It adds one after using the value. Use pre-increment instead.
- Listen for a single change, otherwise you will loop, because
setValue()
will cause the listener for fire again, and again, etc.
As Frank notes, a Transaction is the better way to safely modify counters.
finalDatabaseReferencemRootRef= FirebaseDatabase.getInstance().getReference();
finalDatabaseReferencemCounterRef= mRootRef.child("counter");
// listen for single change
mCounterRef.addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
// getValue() returns Longlongcount= (long) dataSnapshot.child("count").getValue();
System.out.println("count before setValue()=" + count);
mCounterRef.child("count").setValue(++count); // <= Change to ++count
System.out.println("count after setValue()=" + count);
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
// throw an error if setValue() is rejectedthrow databaseError.toException();
}
});
Update for edited question:
You probably need to update your security rules to allow write access. Add a completion listener to see if setValue()
is failing:
mCounterRef.child("count").setValue(++count, newDatabaseReference.CompletionListener() {
@OverridepublicvoidonComplete(DatabaseError databaseError,
DatabaseReference databaseReference) {
if (databaseError != null) {
System.out.println("Error: " + databaseError.getMessage());
}
}
});
Post a Comment for "How To Increment Number In Firebase"