Reputation: 437
I am using Android studio and Firebase to develop an application. I want to store a score in the database if the value is greater than the score in database. How do I check for that?
userData.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
userData.child("score").setValue(count);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Upvotes: 0
Views: 97
Reputation: 191844
You use the dataSnapshot
to get the value from the reference.
Then, use that reference to update the data as you have, but add the conditional.
userData.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String scoreKey = "score";
Long oldScore = dataSnapshot.child(scoreKey).getValue(Long.class);
if (oldScore == null || count > oldScore) {
userData.child(scoreKey).setValue(count);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Upvotes: 1