首页 > 解决方案 > 加载完成后如何将数据加载到 ArrayList 中

问题描述

加载完成后如何将数据加载到 ArrayList 中?

我面临同样的问题。日志:D/DB:[]

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

我怎样才能解决这个问题。先感谢您。

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 );

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


如果您在调试器中运行当前代码并设置一些断点,您会看到它Log.d("DB", String.valueOf(questions))在任何questions.add(question). 这是因为数据是从 Firestore(和大多数现代云 API)异步加载的。

所有需要访问数据库数据的代码都需要在onComplete块内。所以像:

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 );
            }
        }
    });

另见:


推荐阅读