Ghost_Stark Ghost_Stark - 3 months ago 51
Android Question

How to get data from Real-Time Database in Firebase

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

->users
->uid
->name
->email
->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...);
mDBRef.child("users").child(mFirebaseUser.getUid()).setValue(user);


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

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
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
    new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get user value
            User user = dataSnapshot.getValue(User.class);

            //user.email now has your email value
        }
    });