简体   繁体   中英

How to get user information from user node using authentication UId in firebase for android?

I used firebase email/password authentication for login. And I used a user node to store the user data. I could pass the authentication Uid to different activities using shared preferences. How could I get the user info like name, phone, etc. by using this UId?

NB: User info is stored in user node, and UId is from authentication.

I tried the following method, But UName, UMobile, and UEmail shows null value. I could get the UId correctly.

 FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser() ;
 String UId = currentUser.getUid();
 String UName = currentUser.getDisplayName();
 String UMobile = currentUser.getPhoneNumber();
 String UEmail = currentUser.getEmail();

When you store user data,store it with uid. just like json object. uid as key and user data as value. Then you can get the firebaseDatabasereference using this uID.

 {
"users": {
"uid_of_first_user": {
  "username": "usernam",
  "email": "bobtony"
},
 "uid_of_second_user": {
  "username": "usernam",
  "email": "bobtony"
},

}}

use the below code to get the value

  FirebaseDatabase database = FirebaseDatabase.getInstance();
  DatabaseReference myRef = database.getReference("users/uid_of_first_user");

   // Read from the database
   myRef.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
    // This method is called once with the initial value and again
    // whenever data at this location is updated.
    User value = dataSnapshot.getValue(User.class);
    Log.d(TAG, "Value is: " + value);
  }

   @Override
    public void onCancelled(DatabaseError error) {
    // Failed to read value
    Log.w(TAG, "Failed to read value.", error.toException());
}

});

create User.class. Each variables name must be same as in firebase. and also dont forget to create default constructor. just like below

  public class User {
     String username;
     String email;

     public User() {
     }
     public User(String username, String email) {
     this.username = username;
     this.email = email;
     }

   }

if you want to get all users data. Follow the below code.

  FirebaseDatabase database = FirebaseDatabase.getInstance();
  DatabaseReference myRef = database.getReference("users");

  myRef.addValueEventListener(new ValueEventListener() {
  @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
        // TODO: handle the post
          User value = userSnapshot.getValue(User.class);
    }
 }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    // Getting Post failed, log a message
    Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
    // ...
  }
 });

Please take a look at this guide, pay attention to FirebaseAuth.AuthStateListener()

https://www.androidhive.info/2016/06/android-getting-started-firebase-simple-login-registration-auth/

If you are storing the user in a node using the UID and other custom fields then you won't get them with FirebaseAuth. You need to query the tree holding your users with this UID and parse the user data snapshot. Only the UID can be retrieved using FirebaseAuth.

override onAuthStateChanged listener:

mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            if (firebaseAuth.getCurrentUser() != null) {

                //show_snackbar("logged on: " + firebaseAuth.getCurrentUser().getEmail(), Snackbar.LENGTH_SHORT);

                Uri img = firebaseAuth.getCurrentUser().getPhotoUrl();
                Picasso.with(context).load(img).into(account_image);

                account_name.setText(firebaseAuth.getCurrentUser().getDisplayName());

            }
        }
    };

Check This Code. It will Not run but if you know Firebase you will understand it easily. FriendlyChat . Read the comments. or just download the full code, get json file and test it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM