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



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

我也面临同样的问题。Log: 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 );

如果您在调试器中运行当前代码并设置一些断点,您将看到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 );
}
}
});

也看到:

  • 如何检查firestore中是否存在某个数据
  • Firebase Firestore从collection中获取数据

最新更新