0

So I'm using firestore to store data about ingredients and I've been able to add, delete, and get all the items in the database but I can't figure out search and get a single document snapshot. I feel like the code should work so I'm lost.

This is what I tried

public Ingredient searchForIngredient(String ingredient) {
    Log.d(TAG,ingredient);
    ArrayList<Ingredient> retrieved = new ArrayList<Ingredient>();
    ingredientsDB.document(ingredient).addSnapshotListener(new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
            Log.d(TAG, "on event");
            Ingredient ingredient =  createIngredient(value);
            retrieved.add(ingredient);
        }
    });
    
    Ingredient ingredient1 = retrieved.get(0);
    return ingredient1;
}

And what I was expecting is for the "on even" to show up in logcat but it doesn't

  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 27 '22 at 05:44
  • There is no way you can return the `ingredient1` object as a result of a method. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953). – Alex Mamo Oct 27 '22 at 11:28

0 Answers0