0

I know that the Firestore is based on A-sync functions. However, I am trying to retrieve a list and use it outside the function.

private List<CategoriesModel> ourLists(){
    List<CategoriesModel> categoriesModels = new ArrayList<CategoriesModel>();
    db.collection("categories")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            CategoriesModel cat = new CategoriesModel(document.toObject(CategoriesModel.class));
                            categoriesModels.add(cat);
                        }
                        Log.d(TAG, categoriesModels.toString());
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
    Log.d("end", categoriesModels.toString());
    return categoriesModels;
}

How do I wait for the given call and use the data that is inside the "void" function?

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Moty D
  • 43
  • 5
  • https://stackoverflow.com/questions/57330766/why-does-my-function-that-calls-an-api-return-an-empty-or-null-value – a_local_nobody Jun 11 '21 at 14:41
  • Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a custom callback. – Alex Mamo Jun 12 '21 at 10:47

1 Answers1

0

Declare List<CategoriesModel> categoriesModels = new ArrayList<CategoriesModel>(); as global variable in your class.

After the addOnCompleteListener call your call your another function to use this data on UI. E.g

public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            CategoriesModel cat = new CategoriesModel(document.toObject(CategoriesModel.class));
                            categoriesModels.add(cat);
                        }
                        onDataLoaded();
                        Log.d(TAG, categoriesModels.toString());
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
void onDataLoaded() {
   // Your Logic
}
Muhammad Ahmed
  • 1,038
  • 1
  • 7
  • 7