user10431501
user10431501

Reputation: 153

Android Firebase Database keeps updating value

I am trying to take a authors score from the Firebase realtime database. I succesfully get the score value. Then I add 100 onto this value and insert the new value, however when i insert the score value keeps increasing by 100 for example if the score was at 500 instead of changing to 600 it will change to 600, then 700, then 800 etc. If i display a Toast in the addExtraScore method it will display once and as intended.

Activity

private void getAuthorScore()
    {
        database = FirebaseDatabase.getInstance().getReference();
        database.child("Users").child(authorID).addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                User author = dataSnapshot.getValue(User.class);

                authorScore = author.getScore();

                addExtraScore();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError)
            {

            }
        });
    }

    private void addExtraScore()
    {
        int score = authorScore + 100;

        FirebaseUtil.updateUsersScore(authorID, score);
    }

Firebase Util private static DatabaseReference db;

public static void updateUsersScore(String id, int score)
{
    db = FirebaseDatabase.getInstance().getReference();
    db.child("Users").child(id).child("score").setValue(score);
}

Upvotes: 1

Views: 735

Answers (2)

Mr Etineh
Mr Etineh

Reputation: 1

use .addValueEventListener if you want it to change a value anything another value changes

use .addListenerForSingleValueEvent when you want it to change only when clicked.

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138824

To solve this, please change the following line of code:

database.child("Users").child(authorID).addValueEventListener(/* ... */);

to

database.child("Users").child(authorID).addListenerForSingleValueEvent(/* ... */);

To get the data only once. Using addValueEventListener() it means that you are getting the data in realtime and for every change onDataChange() is called again.

Upvotes: 2

Related Questions