问题
public void getFoodItem( String foodNum) {
dbReference=firebaseDatabase.getReference("Food"+foodNum);
dbReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
FoodItem foodItem = dataSnapshot.getValue(FoodItem.class);
Log.d("h", "Gotdata" + foodItem.getImage());
//Data can be taken from here, assigning to a global variable results null
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I can get data using the onDataChange()
method but I can not figure out a way to catch the foodItem object in a global scope. I need to return the foodItem object. How can I do it?
回答1:
Define an interface:
interface FoodListener {
void onFoodReceived(FoodItem foodItem);
void onError(Throwable error);
}
Then modify your method:
public void getFoodItem(String foodNum, final FoodListener listener) {
dbReference=firebaseDatabase.getReference("Food"+foodNum);
dbReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
FoodItem foodItem = dataSnapshot.getValue(FoodItem.class);
Log.d("h", "Gotdata" + foodItem.getImage());
listener.onFoodReceived(foodItem);
}
@Override
public void onCancelled(DatabaseError databaseError) {
listener.onError(databaseError.toException());
}
});
}
Now, callers of the getFoodItem()
method can pass a listener that will be called either when the food is retrieved or when an error occurs.
回答2:
The call to addValueEventListener is asynchronous, so you can update your UI when the data is received in the onDataChange()
method.
If you want to store it in a global variable just declare it outside the method and update on the callback:
private FoodItem foodItem;
public void getFoodItem(String foodNum){
// ...
dbReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
foodItem = dataSnapshot.getValue(FoodItem.class);
// now update the UI
}
// ...
}
来源:https://stackoverflow.com/questions/48501384/how-can-i-return-a-value-from-firebase-in-android