2016-07-07 63 views
1

我剛開始使用Firebase,我很驚訝複雜事情的簡單性以及簡單事情的複雜程度。如何獲取Firebase數據庫的一次值(Android)

我需要檢查用戶是否存在於我的Firebase數據庫中,如果存在,我需要獲取其密鑰和值。

我有鑰匙,我試圖找到它在DB轉到我的用戶子樹,並使用相同的密鑰尋找熱塑成型的孩子(ID)

DatabaseReference root_firebase = FirebaseDatabase.getInstance().getReference(); 
DatabaseReference users_firebase = root_firebase.child("Users"); 
DatabaseReference friend_found = users_firebase.child(key_searched_friend); 

一旦我有它我打電話有的像

friend_found.getValue(); 

friend_found.child("user_name").getValue(); 

但是方法不存在,

這似乎不可思議,因爲我既可以做

friend_found.getKey(); 
friend_found.child("user_name").getKey(); 

我不能與覆蓋方法做到這一點onDataChanged(),因爲當我查詢這個值的數據不會改變。

這是我的火力點的數據庫結構:

{ 
    "RoomNames" : { 
    "Room-KM5cof0jcoMN8a4g6vC" : { 
     "room_name" : "TESTrOOM" 
    }, 
    "Room-KM5dg_WPRdEOT4_oJ1r" : { 
     "room_name" : "testRoom2" 
    } 
    }, 
    "Users" : { 
    "User-KM5ZaGq0xvjQis05CPF" : { 
     "user_name" : "Enrique" 
    } 
    } 
} 

回答

5

你說:我不能與覆蓋方法做到這一點onDataChanged(),因爲當我查詢這個值

數據不會改變

對於如何Retrieve Data導解釋說:

Firebase data is retrieved by attaching an asynchronous listener to a FirebaseDatabase reference. The listener is triggered once for the initial state of the data and again anytime the data changes.

所以,當你附加一個偵聽人發生,onDataChanged()發生火災,併爲您提供當前值。

在題爲讀取數據的部分一次,指南指出:

In some cases you may want a callback to be called once and then immediately removed, such as when initializing a UI element that you don't expect to change. You can use the addListenerForSingleValueEvent() method to simplify this scenario: it triggers once and then does not trigger again.

+0

我不明白這將是有益的,因爲每一個用戶被添加到數據庫時,也將其添加爲朋友,其他nosql DB讓我在數據庫的任何部分使用.getValue()或.exists()我沒有看到阻止此功能的任何優勢,儘管我確定它們是。 –

+0

也從他們自己的文檔的代碼甚至沒有編譯[linkToTheirCode](https://www.firebase.com/docs/android/guide/retrieving-data.html#section-reading-once),它抱怨說onClancelled必須實施,然後取消不能被覆蓋。 (143,88)錯誤:不是抽象的,並且不覆蓋ValueEventListener中的抽象方法onCancelled(DatabaseError) 錯誤:(148,21)錯誤:方法不會覆蓋或實現超類型的方法「 –

+1

您的鏈接是舊文檔。如果您使用的是Firebase 9.x.x,則需要引用[ValueEventListener的新文檔](https://developers.google.com/android/reference/com/google/firebase/database/ValueEventListener)。 'onCancelled()'的參數類型已更改。 –

相關問題