Android - onDataChange()奇怪的行为

时间:2017-02-14 08:50:40

标签: android firebase firebase-realtime-database

我使用Firebase创建了一个应用。有一个问题我无法解决,也没有在这里找到它。

在这个方法中,我想检查一些数据是否已经在服务器中。如果没有 - 我想添加它(添加代码运行良好.Firebase数据库正在根据需要进行更改)。所以我使用onDataChange方法如下:

public boolean insertNewList(String title)
{
    System.out.println("start: ");

    final boolean[] result = new boolean[1];
    result[0]=false;

    final String group = title;

    mRootRef = some reference...



    mRootRef.addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {

            System.out.println(0);

            if (dataSnapshot.child(group).getValue() != null)
            {
                System.out.println(group + " is already exist");
                System.out.println(1);

            }

            //write the data.
            else
            {
                mRootRef=mRootRef.child(group);
                mRootRef.push().setValue("some data");
                System.out.println(2);
                result[0]=true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError)
        {

        }
    });


    System.out.println(3);

    return result[0];
}

但真正发生的是这个输出:

begin:
3 (just skip on onDataChange method and return false).
some print after calling the function
0 (goes back to function and enter to onDataChange method)
2 (finally goes where I want it to go)
0 (for some reason enters twice  :(   )
1  

因此我在这个功能中收到了错误的结果。 你能帮忙吗?

2 个答案:

答案 0 :(得分:0)

替换

mRootRef.addValueEventListener(new ValueEventListener()

mRootRef.addListenerForSingleValueEvent(new ValueEventListener()

将值添加到firebase时," addValueEventListener"再次调用,而不是像addListenerForSingleValueEvent那样只拍摄一次。

答案 1 :(得分:0)

您向我们展示的输出看起来很正常。让我试着解释一下:

begin: // a) this comes from the System.out.println("begin")
3      // b) you DECLARE your value event listener and then you run
       // the System.out.print("3") statement
0      // c) you just added a listener so firebase calls you, and
       // your listener fires
2      // d) this is the first time your listener fires, so you go
       // into the block called "write the data"
0      // e) since you just wrote the data, firebase calls you again
1      // f) this time, since the data has been written, you go into
       // the block called "is alraedy exist"

这是firebase的正常行为。 在c)中,当你声明一个监听器时,firebase总是给你回电话。 在e)中,firebase会因为数据发生变化而调用您。 但是在b)中,你只是声明你的监听器,还没有运行它,所以执行这个声明之后的语句并且在其他任何事情发生之前你会看到“3”。

相关问题