Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

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

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 );
question from:https://stackoverflow.com/questions/66064127/how-to-load-data-into-an-arraylist-after-its-finished-loading

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...