I have a static method that gets all the documents in a collection. I am having trouble creating an array of these documents to return. How could I do that? Let us call the Array list 'allItems'. My approach was to add each item that is created inside the for loop to an the allItems array list, but this list is null when I return it and android studio is prompting me to make the array list final.
public static ArrayList<Item> geAllFromFireStore() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
ArrayList<Item> allItems = new ArrayList<>();
db.collection("Items")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
String name = document.get("name") + "";
String categoryName = document.get("category") + "";
Item item = new Item(name, category);
// I would like to add these items to an array list and return that array list
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
return allItems;
}