Java 是否可以在不附加任何侦听器的情况下读取 Firebase 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22323242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to read Firebase data without attaching any listeners?
提问by shazeline
I'm working on a Firebase Android app and need a way to read data from Firebase without actually attaching any listeners. I don't care in this particular instance if the data changes after the initial read. Is there a way I can directly access a DataSnapshot
without attaching an EventListener to a Firebase reference? Or is there some other way I can directly read from a Firebase reference with some sort of ref.getValue()
equivalent?
我正在开发 Firebase Android 应用程序,需要一种从 Firebase 读取数据而不实际附加任何侦听器的方法。在这种特殊情况下,我不在乎数据在初始读取后是否发生变化。有没有一种方法可以直接访问 aDataSnapshot
而无需将 EventListener 附加到 Firebase 引用?或者有没有其他方法可以直接从 Firebase 引用中读取某种ref.getValue()
等价物?
Thank you.
谢谢你。
回答by Frank van Puffelen
You can use Firebase's REST API to get access to the "raw" data.
您可以使用 Firebase 的 REST API 来访问“原始”数据。
From: https://www.firebase.com/docs/rest-api.html
来自:https: //www.firebase.com/docs/rest-api.html
You can use any Firebase URL as a REST endpoint. All you need to do is append ".json" to the end of the URL and send a request from your favorite HTTPS client. Note that HTTPS is required. Firebase only responds to encrypted traffic so that your data remains safe.
您可以使用任何 Firebase URL 作为 REST 端点。您需要做的就是将“.json”附加到 URL 的末尾,并从您最喜欢的 HTTPS 客户端发送请求。请注意,HTTPS 是必需的。Firebase 仅响应加密流量,以确保您的数据安全。
curl https://SampleChat.firebaseIO-demo.com/users/Hyman/name.json
A successful request will be indicated by a 200 OK HTTP status code. The response will contain the data being retreived:
成功的请求将由 200 OK HTTP 状态代码指示。响应将包含正在检索的数据:
{"first":"Hyman", "last": "Sparrow"}
That same page also mentions a Java wrapper project: https://github.com/bane73/firebase4j
同一页面还提到了一个 Java 包装器项目:https: //github.com/bane73/firebase4j
回答by Kato
The the Java SDKprovides a addListenerForSingleValueEvent
method, which is equivalent to your ref.getValue(). It is utilized just like addValueEventListener
, but only retrieves a single value.
在Java SDK中提供了一个addListenerForSingleValueEvent
方法,这相当于你ref.getValue()。它的使用方式与 类似addValueEventListener
,但仅检索单个值。
fb.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snap) {
System.out.println(snap.getName() + " -> " + snap.getValue());
}
@Override public void onCancelled() { }
});
The REST API, as Frank mentioned, is also a great choice.
正如 Frank 所提到的,REST API 也是一个不错的选择。