Ghost_Stark Ghost_Stark - 1 year ago 152
Android Question

How to get data from Real-Time Database in Firebase

I've used the Real-Time Database with this setup:

->other info

If I wanted to save the user data I would use my User class and then set the object in the database like this:

//assume variables have already been declared...

mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
User user = new User(name, email, other values...);

I tried it and it works fine.

But how can I retrieve these values from the database? For instance, once I set a User object as shown above, I may want to retrieve the user's email. I don't mean getting the email through the sign-in provider. I want the email through the real-time database. I've tried working this out for a while now but the documentation isn't helping much. All it shows is to setup listeners in order to wait for changes to the data. But I'm not waiting for changes, I don't want a listener. I want to directly get the values in the database by using the keys in the JSON tree. Is this possible via the real-time database? If so, how can it be done because either the documentation doesn't explain it or I'm just not understanding it. If not possible, am I supposed to be using the Storage database or something else? Thanks.

Answer Source

Firebase uses listeners to get data. That is just the nature of how it works. Although, you can use a single event listener (the equivalent of just grabbing the data once). It will fire immediately and get the data, and will not fire ever again. Here's a code example to get the current user's email:

//Get User ID
final String userId = getUid();

//Single event listener
    new ValueEventListener() {
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get user value
            User user = dataSnapshot.getValue(User.class);

            // now has your email value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download