我正在尝试从数据库中下载一些测验对象。 从某个活动的onCreate调用以下函数。
private void downloadQuizzesFromCloud(){
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
String user_quizzes_path = "users/".concat(user_id).concat("/quizzes");
Query userQuizzes = db.collection(user_quizzes_path);
userQuizzes.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
quizzes.clear();
for (QueryDocumentSnapshot document : task.getResult()) {
Quiz quizDownloaded = getQuizFromCloud(document.getId());
quizzes.add(quizDownloaded);
}
Toast.makeText(QuizzesActivity.this,"downloaded to list ".concat(String.valueOf(quizzes.size()).concat(" quizzes")), Toast.LENGTH_SHORT).show();
//TODO put in recycle adapter
} else { }
}
});
}
(user_quizzes_path包含指向存储在云中的Quiz对象的正确路径)
我调试了此功能,并在命令后发现:
userQuizzes.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>()
该函数完成执行,即不检查和执行onComplete情况,而仅跳过所有这些代码。
我试图在firebase的文档中找到它,但是什么也没找到。 为什么会发生这种情况,我该如何解决?
在此感谢您的帮助,
答案 0 :(得分:1)
从Firestore服务器完成读取操作后,将调用onComplete
。如果没有被调用,我可以看到两个可能的原因:
get()
到触发onComplete
可能需要一段时间。要测试是否存在这种情况,请在if (task.isSuccessful()) {
上放置一个断点,然后在调试器中运行该应用程序。从服务器读取数据时,断点将到达。答案 1 :(得分:0)
使用回调接口。就像下面这样。
private void downloadQuizzesFromCloud(Consumer listener) {
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
String user_quizzes_path = "users/".concat(user_id).concat("/quizzes");
Query userQuizzes = db.collection(user_quizzes_path);
userQuizzes.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Quiz> quizzes = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
Quiz quizDownloaded = getQuizFromCloud(document.getId());
quizzes.add(quizDownloaded);
}
listener.onGet(quizzes);
Toast.makeText(QuizzesActivity.this,"downloaded to list ".concat(String.valueOf(quizzes.size()).concat(" quizzes")), Toast.LENGTH_SHORT).show();
//TODO put in recycle adapter
} else { }
}
});
}
interface Consumer {
void onGet(List<Quiz> quizzes);
}