Ikiugu
Ikiugu

Reputation: 677

How to handle results from Firebase seeing that its aynchronous

How do I return combinedFoodItem from the code below. I have been using firebase for less than a week now and I still find this confusing. The summary is: Food contains name and categoryId (which is from the FoodOption model)

public void getFoodItems() {

    //get all the food options for the selected venue
    final List<FoodItem> combinedFoodItem = new ArrayList<>();

    filterRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                final FoodOption foodOption = dataSnapshot1.getValue(FoodOption.class);
                final List<Food> foodList = new ArrayList<>();

                meniItemFilter = menuItemReference.orderByChild("categoryId").equalTo(foodOption.getKey());

                meniItemFilter.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        for (DataSnapshot dataSnapshot2 : dataSnapshot.getChildren()) {

                            Food food = dataSnapshot2.getValue(Food.class);

                            foodList.add(food);

                        }
                        FoodItem foodItem = new FoodItem(foodOption.getFoodCategory(), foodList, R.drawable.ic_banjo);
                        combinedFoodItem.add(foodItem);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }

                });

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

Upvotes: 0

Views: 36

Answers (1)

Marc MF
Marc MF

Reputation: 36

as firebase works in a reactive manner you can't return elements but listen for changes of them. You can define your combinedFoodItem outside the function (this is, for instance, as a class field) and then add the elements to the list (or clear the list every time the data changes if you want to reset the list this depends on the behavior of your list)

Upvotes: 1

Related Questions