java - 加载完成后如何将数据加载到 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 );
解决方案
如果您在调试器中运行当前代码并设置一些断点,您会看到它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 );
}
}
});
另见:
推荐阅读
- angular - Angular 8-组件销毁时HTTP请求被取消-如何防止这种情况?
- c - 如何读取块设备直到最后一个字节
- sql - 如何在 PostgreSQL 函数中运行许多与插入相关的数据?
- php - 我可以加入两个数组 - PHP
- html - CSS:选择具有特定类的下一个元素
- ios - Alamofire 5.0.0-rc.3 RequestInterceptor Adapt 方法没有被调用 Alamofire 虽然在响应中有任何错误时会调用重试
- ios - 未调用 iOS 回调的 FCM 推送
- c# - 如何在 c# windows 窗体中使用计时器仅在按下按钮时才上下移动电梯?
- clojurescript - 带有 cljsjs/react-day-picker 的 Clojurescript 日期时间选择器
- bash - 检查特定名称服务器上是否存在 dns-zone