如何一次获取Firebase数据库的值(Android) [英] How to get a value once of a firebase database (Android)
问题描述
我刚开始使用firebase,我对复杂的事物有多么简单,以及多么简单的事物感到惊讶.
I just started using firebase and I'm amazed of how simple are complex things, and how complex simple things can be.
我需要检查Firebase数据库中是否存在用户,如果存在,则需要获取其键和值.
I need to check if a user exists in my Firebase database, and if exists, I need to get its key and value.
我有密钥,我尝试通过转到用户子树并寻找具有相同密钥(ID)的孩子来在数据库中找到它
I have the key and I try to find it in the DB by going to my user subtree and loking for a child with the same key (ID)
DatabaseReference root_firebase = FirebaseDatabase.getInstance().getReference();
DatabaseReference users_firebase = root_firebase.child("Users");
DatabaseReference friend_found = users_firebase.child(key_searched_friend);
一旦有了,我就会尝试调用类似的方法
once I have it I try to call some method like
friend_found.getValue();
或
friend_found.child("user_name").getValue();
但是它不存在,
这看起来很奇怪,因为我可以两者都做
this seems weird since I can do both
friend_found.getKey();
friend_found.child("user_name").getKey();
我无法使用重写方法onDataChanged()来执行此操作,因为查询此值时数据不会更改.
I can't do this with the overriden method onDataChanged() since the data does not change when I query for this value.
这是我的firebase数据库结构:
This is my firebase database structure:
{
"RoomNames" : {
"Room-KM5cof0jcoMN8a4g6vC" : {
"room_name" : "TESTrOOM"
},
"Room-KM5dg_WPRdEOT4_oJ1r" : {
"room_name" : "testRoom2"
}
},
"Users" : {
"User-KM5ZaGq0xvjQis05CPF" : {
"user_name" : "Enrique"
}
}
}
推荐答案
您说:我无法使用覆盖方法onDataChanged()来执行此操作,因为查询该值时数据不会更改
有关获取数据的指南说明:>
The guide for how to Retrieve Data explains that:
通过将异步侦听器附加到FirebaseDatabase参考.会在一次触发监听器数据的初始状态,并在数据更改时再次显示.
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()触发并为您提供当前值.
So when you attach a listener to a location, onDataChanged() fires and gives you the current value.
在标题为一次读取数据"的部分中,指南指出:
In the section titled Read Data Once, the guide states:
在某些情况下,您可能希望一次调用一次回调立即删除,例如初始化您的UI元素时不要指望改变.您可以使用 addListenerForSingleValueEvent()方法可简化此情况:触发一次,然后不再触发.
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.
这篇关于如何一次获取Firebase数据库的值(Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!