0

How to load data into an ArrayList after it's finished loading ?

I am facing the same issue. Log : D/DB: []

https://www.reddit.com/r/Firebase/comments/d1dyd4/androidfirebase_how_to_load_data_into_an/

How can I fix this. Thank you in advance.

db.collection("fastmode")
    .get()
    .addOnCompleteListener(new OnCompleteListener < QuerySnapshot > () {
        @Override
        public void onComplete(@NonNull Task < QuerySnapshot > task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot documentSnapshot: task.getResult()) {
                    String question = documentSnapshot.getString("question");
                    String answer = documentSnapshot.getString("answer");

                    Log.d("DB", question);
                    Log.d("DB", answer);
                    questions.add(question);
                }
            }
        }
    });

Log.d("DB", String.valueOf(questions));
Intent in = new Intent(getApplicationContext(), FastMode.class);
startActivity( in );
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

If you run your current code in a debugger and set some breakpoints, you'll see that Log.d("DB", String.valueOf(questions)) runs before any of the questions.add(question). This is because data is loaded from Firestore (and most modern cloud APIs) asynchronously.

All code that needs access to the data from the database needs to be inside the onComplete block. So something like:

db.collection("fastmode")
    .get()
    .addOnCompleteListener(new OnCompleteListener < QuerySnapshot > () {
        @Override
        public void onComplete(@NonNull Task < QuerySnapshot > task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot documentSnapshot: task.getResult()) {
                    String question = documentSnapshot.getString("question");
                    String answer = documentSnapshot.getString("answer");

                    Log.d("DB", question);
                    Log.d("DB", answer);
                    questions.add(question);
                }
                Log.d("DB", String.valueOf(questions));
                Intent in = new Intent(getApplicationContext(), FastMode.class);
                startActivity( in );
            }
        }
    });

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807