Reputation: 17
I am trying to show the details of the current user logged in. I have tryed a few methods to try and solve this but all it seems to return is null. My user firebase database is :
Where am i going wrong ?
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
Button mBeerButton;
Button mBeerButtonTwo;
Button mBeerButtonThree;
Button mBeerButtonFour;
Button mSignOutButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
String mUserID = firebaseAuth.getCurrentUser().getUid();
DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("Users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String mUsername = dataSnapshot.child("mUserName").getValue().toString();
Toast.makeText(homeScreen.this,"User name is "+ mUsername,Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Upvotes: 1
Views: 45
Reputation: 598728
As an alternative to Yunus answer (which works fine if you know the key of the node you want to show), here's how you can get all nodes under Users
and then iterate over the child nodes:
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
String mUsername = userSnapshot.child("mUserName").getValue(String.class);
Toast.makeText(homeScreen.this,"User name is "+ mUsername,Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
Upvotes: 0
Reputation: 1022
Look at your JSON structure. You are skipping one of the nodes. Change it as follows:
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String mUsername = dataSnapshot.child("JoBlogsUser").child("mUserName").getValue().toString();
Toast.makeText(homeScreen.this,"User name is "+ mUsername,Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Upvotes: 1