问题
I have been trying to retrieve data fields from my firebase database for the past 5 days without any success. This is what my database looks like:
Code for fetching data:
private void alterTextView(final String id) {
if(id!=null) {
mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInformation userInformation = dataSnapshot.getValue(UserInformation.class);
String name = (String) userInformation.getName();
Log.d("Main Activity",name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mWelcomeUserMessage.setText("Welcome, "+name);
}
}`
I have no idea why the name is 'null' (refer to log). Can someone tell me what I'm doing wrong?
PS: I have defined a blank default constructor, getters, and setters in my UserInformation.java class.
Also, mDatabase is initialized as follows:
mDatabase = FirebaseDatabase.getInstance().getReference();
回答1:
dataSnapshot.getValue(Class) will only load and set values into public fields. I see you already have a default constructor.
Make name field in UserInformation class public. Also make sure the snapshot you are calling getValue on is a valid JSON representation of UserInformation class and has an exact same "name" field (it must exactly match the name field in class).
Please note:
addValueEventListener adds a listener, which will be called when data is available.
Please note that the data is available after onDataChange has been called. That's why you should set your text right after you get the data you need from the DataSnapshot. Like that:
private void alterTextView(final String id) {
if(id!=null) {
mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInformation userInformation = dataSnapshot.getValue(UserInformation.class);
String name = (String) userInformation.getName();
Log.d("Main Activity",name);
runOnUiThread(new Runnable() {
@Override
public void run(){
mWelcomeUserMessage.setText("Welcome, "+name);
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
来源:https://stackoverflow.com/questions/44389278/not-able-to-retrieve-data-field-from-firebase-database