dataSnapshot.getChildren() gets the user ID but does not get the value… here is a solution to the problem.
dataSnapshot.getChildren() gets the user ID but does not get the value
When you run this code:
private void getData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Log.d(TAG, "UserID inside getData: "+userID);
Log.d(TAG, "User Name inside getData: "+ds.child(userID).child("name").getValue());
Log.d(TAG, "DS inside getData: "+ds.child(userID));
hospitalCity = String.valueOf(ds.child(userID).child("city").getValue());
Log.d(TAG, "User city inside getData: "+ds.child(userID).child("city").getValue());
break;
}
}
The log shows:
UserID inside getData: Lsncj8CIsfTQXc7E425AtLuDI5v2
User Name inside getData: null
DS inside getData: DataSnapshot { key = Lsncj8CIsfTQXc7E425AtLuDI5v2, value = null }D/DonorList: User city inside getData: null
Here is the database:
As you can see, it gets the key, but the value is null
, although the database shows that there is a value in it.
Solution
In order to obtain the data under the Hospital
node, you need to modify the following reference:
hospitalDatabase = FirebaseDatabase.getInstance().getReference();
with
hospitalDatabase = FirebaseDatabase.getInstance().getReference().child("Hospital");
To get the data in the getData()
method, use the following code:
private void getData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
String city = ds.child("city").getValue(String.class);
String name = ds.child("name").getValue(String.class);
}
}
ds.getKey()
returns userId
ds.child("city").getValue(String.class)
will return the city.
ds.child("name").getValue(String.class)
returns the name.