2017-02-14 59 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