0

I am new, any one can help me, I am trying to get data from firestore, data is retrieving and I viewed in Log but in the list that I am trying to initialize.

Here is my code:

public List<TestQuestion> getListOfQuestions() {
        listOfQuestions = new ArrayList<>();
        db.collection("TestQuestions")
                .whereEqualTo("test_level",1)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                listOfQuestions.add(document.toObject(TestQuestion.class));
                                Log.d(TAG, "Questions = " + document.getData());
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
        return listOfQuestions;
    }

In Log

D/ContentValues: Questions = {option_d=op d, option_b=op b, option_c=op c, question=my first question, subject=English, test_level=1, right=1, option_a=op a} D/ContentValues: Questions = {option_d=op d, option_b=op b, option_c=op c, question=my second question, subject=English, test_level=1, right=2, option_a=op a} D/ContentValues: Questions = {option_d=op d, option_b=op b, option_c=op c, question=my third question, subject=English, test_level=1, right=2, option_a=op a}

listOfQuestions size is 0

Sidra Kanwal
  • 115
  • 9
  • 1
    Your `listOfQuestions` size is 0 because you are returning it immediately before the `onComplete` method is executed. – Nongthonbam Tonthoi Apr 27 '20 at 17:08
  • @Nongthonbam Tonthoi kindly guide what I have to do to solve this problem – Sidra Kanwal Apr 27 '20 at 17:12
  • 1
    It depends on what you are doing with `listOfQuestions` and from where you are calling `getListOfQuestions()`. You can create an interface as callback listener if you are calling from different class other just do your logic after the `for` loop in the `onComplete` method – Nongthonbam Tonthoi Apr 27 '20 at 17:18
  • Firebase API is asynchronous. So please check the duplicate to how can you solve this using a custom callback. – Alex Mamo Apr 28 '20 at 07:28
  • @Nongthonbam Tonthoi Thanks dear I have done by call back listener. – Sidra Kanwal Apr 28 '20 at 08:55

0 Answers0