Reputation:
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());
}
});
Upvotes: 2
Views: 4201
Reputation: 138824
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());
}
});
Upvotes: 2
Reputation: 335
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();
}
}
};
Upvotes: 0