简体   繁体   English

Android Firebase数据库不断更新价值

[英]Android Firebase Database keeps updating value

I am trying to take a authors score from the Firebase realtime database. 我正在尝试从Firebase实时数据库中获得作者评分。 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. 然后我在这个值上加上100并插入新值,但是当我插入得分值时,例如,如果得分为500(而不是600)而不是更改为600,它将更改为600、700、800。如果我在addExtraScore方法中显示Toast,它将按预期显示一次。

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; Firebase Util私有静态DatabaseReference db;

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

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. 使用addValueEventListener()意味着您正在实时获取数据,并且每次更改onDataChange()都会被再次调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM