Android Firebase数据库不断更新价值 [英] Android Firebase Database keeps updating value

查看:58
本文介绍了Android Firebase数据库不断更新价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Firebase实时数据库中获得作者评分.我成功获得了得分值.然后我在这个值上加上100并插入新值,但是当我插入分数时,例如,如果分数为500,而不是更改为600,它将保持增加100,它将变为600,然后是700,然后是800,依此类推.如果我在 addExtraScore 方法中显示Toast,它将按预期显示一次.

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.

活动

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实用程序私有静态DatabaseReference db;

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);
}

推荐答案

要解决此问题,请更改以下代码行:

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

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

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

仅一次获取数据.使用 addValueEventListener()意味着您正在实时获取数据,并且每次更改 onDataChange()都会被再次调用.

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.

这篇关于Android Firebase数据库不断更新价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆