John
John

Reputation: 437

Android - Insert in DB if value is greater than the value in DB

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

Answers (1)

OneCricketeer
OneCricketeer

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

Related Questions