0
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?

Tashun Sandaru
  • 119
  • 1
  • 9

2 Answers2

2

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.

Minas Mina
  • 2,058
  • 3
  • 21
  • 35
  • Gets a null object Reference. java.lang.NullPointerException: Attempt to invoke virtual method – Tashun Sandaru Jan 29 '18 at 14:26
  • @Waesz your listener is being called every time the data changes, is this what you intended? If you want to query it only once, there a `addListenerForSingleValueEvent()` method. – Minas Mina Jan 29 '18 at 15:39
0

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
        }
        // ...
}
Melk90
  • 370
  • 1
  • 2
  • 8