2016-07-07 64 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()'的参数类型已更改。 –

相关问题