2017-02-14 60 views
0

我使用Firebase创建了一个应用程序。有一个我无法解决的问题,并没有在这里讨论。Android - onDataChange()奇怪的行为

在这种方法中,我想检查一些数据是否已经在服务器中。如果没有 - 我想添加它(添加代码的效果很好,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 

正因为如此我接受这个功能错误的结果。 你能帮忙吗?

+0

对不起,我用“开始”取代了“开始”,但没关系。 – ayelet

回答

0

更换

mRootRef.addValueEventListener(new ValueEventListener() 

mRootRef.addListenerForSingleValueEvent(new ValueEventListener() 

当您添加值,以火力点, “addValueEventListener” 再次呼吁,不喜欢addListenerForSingleValueEvent该出手只有一次anywhy。

+0

谢谢!解决了我的问题,为什么它会进入两次。如果我问服务器是否存在某种价值 - 如果没有,我会添加它,这是没有意义的,他将把它作为2个行为而不是1个。 – ayelet

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”。

+0

感谢您的评论。我现在明白,这种方法不符合我的预期,但正如你所提到的。我认为监听器发生,只有这样 - 从函数返回值。 – ayelet