magnoleal magnoleal - 5 months ago 139
Android Question

Retrieve User Data Firebase on Android

Is there a way to retrieve data from a specific user who is authenticated via firebase through ID?

For example to retrieve information like name, photo etc.

Thanks in advance.

Answer

This is more of a port of the iOS answer i have given here

Firebase provides authentication for users using the FIRAuth Clases/API

However they can't be edited with custom fields like the Firebase Database.

To allow custom fields for user, you need to duplicate users in the Database with the same unique uid you receive in the auth of the user. Something like this

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
  // User is signed in
   String name = user.displayName;
   String email = user.email;
   String photoUrl = user.photoURL;
   String uid = user.uid;


    FirebaseDatabase database = FirebaseDatabase.getInstance();
    String key = database.getReference("users").push().getKey();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put( "uid", uid);
    childUpdates.put( "name", name);
    // other properties here

    database.getReference("users").updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
            if (databaseError == null) {

            }
        }
    });
} 

We push it at the users end point in our db and with the uid key by the following line /users/\(key).

Now you can retrieve users detail from your database by querying anywhere in your code.

Comments