简体   繁体   中英

Get current user details i.e. the user which is logged in firebase

I am developing an application in which I have to get the current user details from the firebase UserNode. In my case I want to get firstname and lastname of the current user. I am successfully getting the list of all users but what to do to get the current user details who is logged in. I use this code to get all users, please guide me what to do in this code to get the current logged in user details

DatabaseReference DataRef;
    DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");

    DataRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                String acctname = (String)childSnapshot.child("firstname").getValue();
                Log.i("name", acctname);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("error", databaseError.getMessage());
        }
    });

To get a particular user, you need to use in your DatabaseReference his unique identifier. So, you need to change this line:

DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode");

with

FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
String uid = firebaseUser.getDisplayName(); //display the entire name
DataRef = FirebaseDatabase.getInstance().getReference().child("UserNode").child(uid);

And please use this code:

DataRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String acctname = childSnapshot.child("firstname").getValue(String.class);
        Log.i("name", acctname);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e("error", databaseError.getMessage());
    }
});

Try this Hope it helps you

 FirebaseAuth auth = FirebaseAuth.getInstance();
        FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
                if (firebaseUser != null) {
                    String userId = firebaseUser.getUid();
                    String userEmail = firebaseUser.getEmail();
                } 
            }
        };

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