0
public void showTotalFreshness(String userID){
    FirebaseFirestore db = FirebaseFirestore.getInstance();

    CollectionReference bigIngredientRef = db.collection("사용자").document(userID)
            .collection("냉동실"); //대분류 Ref

    bigIngredientRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            final long[] addAllDate = {0};
            final int[] num = {0};
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    if (document.exists()) {
                        String bigIngredientName = document.getId();

                        CollectionReference smallIngredientRef = bigIngredientRef.document(bigIngredientName)
                                .collection(bigIngredientName);
                        smallIngredientRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                for(QueryDocumentSnapshot document : task.getResult()) {
                                    long totalEd = document.getLong("유통기한");
                                    addAllDate[0] += totalED; //this is the add code
                                    num[0]++;
                                }
                            }
                        });
                    }

                }
                Log.d("HELLO", addAllDate[0] + " " + num[0]); //it comes out 0
}

I want to add all addAllDate and num inside the addOncompleteListener. But it comes out the first value(0). How can I get all the sum Of values? I want to know the answer!!!

남기훈
  • 11
  • 1
  • Data is loaded from Firestore (and pretty much all cloud APIs) asynchronously. This means that your `Log.d("HELLO", addAllDate[0] + " " + num[0]);` runs before `onComplete` is ever called. You can check this by setting breakpoints and runnin in the debugger. The solution is always the same: all code that needs the data from the database, has to be inside `onComplete`, be called from there, or be otherwise synchronized. – Frank van Puffelen Nov 20 '22 at 17:56
  • thank you for your answer. how to get all the totalED and then print it?? i have to put the value on the textView:text – 남기훈 Nov 21 '22 at 00:35
  • There is no way you can do that. Firebase API is asynchronous. So please check the duplicate answers to see how can you solve this issue. 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 Nov 21 '22 at 09:16

0 Answers0