Android Studio Value Increment In Firebase
Solution 1:
In order to increment a value in a Firebase database, first of all, you need to retrieve that value. There is no way to increment a value without knowing it. To achieve this, I definitely recommend you to use Firebase Transaction.
Let's take an example. Let's assume we want to increment a counter. In order to achieve this, please use the following code to set the default value of the counter.
DatabaseReferencerootRef= FirebaseDatabase.getInstance().getReference();
rootRef.child("score").setValue(1);
Assuming that the score
field is of type Integer, to use transactions, please use the following method:
publicstaticvoidsetScore(String operation) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
scoreRef.runTransaction(newTransaction.Handler() {
@OverridepublicTransaction.ResultdoTransaction(MutableData mutableData) {
Integer score = mutableData.getValue(Integer.class);
if (score == null) {
returnTransaction.success(mutableData);
}
if (operation.equals("increaseScore")) {
mutableData.setValue(score + 1);
} elseif (operation.equals("decreaseScore")){
mutableData.setValue(score - 1);
}
returnTransaction.success(mutableData);
}
@OverridepublicvoidonComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {}
});
}
Using transactions
, you will avoid inconsistent results if users are trying to increase/decrease the score at the same time. So as a conclusion, call this method accordingly to your increase/decrease operation.
If you want to read the score, please use the following code:
DatabaseReferencerootRef= FirebaseDatabase.getInstance().getReference();
DatabaseReferencescoreRef= rootRef.child("score");
ValueEventListenereventListener=newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
Integerscore= dataSnapshot.getValue(Integer.class);
Log.d("TAG", "score: " + score);
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
Solution 2:
- Get the value from the database.
- Make a simple while loop, with the number of increments you need. Declare the variable globally, not within the onCreate methods.
- Set them back to the Database.
Solution 3:
You don't need to retrieve the value if you use ServerValue.increment(). Recently, It landed on Flutter in version firebase_database 4.1.
The way you can use is:
mRefChild.set(ServerValue.increment(1));
Post a Comment for "Android Studio Value Increment In Firebase"