I want to load a dataset oncreate().
Since the data will not change, I use the one time loader:
protected void onCreate(Bundle savedInstanceState) {
....
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.getValue(Users.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "error:", databaseError.toException());
}
});
String name = currentUser.getName();
....
}
But the data is not available, the getName function is called on a null object.
How can I get the data onCreate()?
The problem is that Firebase uses an asynchronous listeners to a database reference, and you set name variable with null currentUser.
Try to declare the name var as final and before the listener, and set his value inside the firebase callback.
Update: an example how to implement and use an "override" function:
final String name;
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.getValue(Users.class);
name = currentUser.getName();
fooFunc(name); // calling a function with data
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "error:", databaseError.toException());
}
});
@Override
public void fooFunc(String name) {
// name != null, when called from the the callback
// dont forget to check it
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With