Reputation: 7
I am trying to retrieve data from my firebase database and print a statement in a text field but I keep getting null values. I'm using the userid
to try and get to the child node that I want. My textfield keeps saying "Welcome null logged-in as null" My Firebase Database
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
final String uid;
FirebaseUser user;
user = FirebaseAuth.getInstance().getCurrentUser();
uid = user.getUid();
DatabaseReference reference =
FirebaseDatabase.getInstance().getReference("User");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
fName = dataSnapshot.child(uid).child("fName").getValue(String.class);
role = dataSnapshot.child(uid).child("role").getValue(String.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
welcomeText = (TextView) findViewById(R.id.welcomeText);
welcomeText.setText("Welcome " + fName + "! You are logged-in as " + role);
Upvotes: 0
Views: 1333
Reputation: 15423
You should pass your userid
as child to get data for only the logged in user. Currently you loop through all the users which gives you wrong data at the end.
Try like below:
DatabaseReference reference =
FirebaseDatabase.getInstance().getReference("User").child(uid);
instead of
DatabaseReference reference =
FirebaseDatabase.getInstance().getReference("User");
Beside this, Currently you are setting the initial value of fName
and role
which is null and never update the value with your user detail which you get inside onDataChange
. So, update your TextView
inside onDataChange
.
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
fName = dataSnapshot.child("fName").getValue(String.class);
role = dataSnapshot.child("role").getValue(String.class);
welcomeText.setText("Welcome " + fName + "! You are logged-in as " + role);
}
Upvotes: 1
Reputation: 453
Move the following lines to the onDataChange() callback method.
welcomeText = (TextView) findViewById(R.id.welcomeText);
welcomeText.setText("Welcome " + fName + "! You are logged-in as " + role);
Upvotes: 1