Is it possible to read Firebase data without attac

2019-01-09 09:39发布

问题:

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?

Thank you.

回答1:

You can use Firebase's REST API to get access to the "raw" data.

From: 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.

curl https://SampleChat.firebaseIO-demo.com/users/jack/name.json

A successful request will be indicated by a 200 OK HTTP status code. The response will contain the data being retreived:

{"first":"Jack", "last": "Sparrow"}

That same page also mentions a Java wrapper project: https://github.com/bane73/firebase4j



回答2:

The the Java SDK provides a addListenerForSingleValueEvent method, which is equivalent to your ref.getValue(). It is utilized just like addValueEventListener, but only retrieves a single value.

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.