【发布时间】:2018-08-22 10:35:48
【问题描述】:
我正在尝试创建一种方法来从我的Cloud Firestore database 中查询项目列表。然后我会用所述列表设置一个RecyclerView 适配器,它应该可以很好地显示。截至目前,RecyclerView 为空。 (我还用虚拟项目测试了RecyclerView,它们显示得很好)
在我的方法结束时,项目列表仍然为空。日志以奇怪的顺序显示(最后一个日志显示在其他日志之前)。日志顺序让我怀疑侦听器中运行了一些单独的线程。我不确定如何同步它们。
private List<Project> projects;
private FirebaseFirestore db;
...在 onCreateView() 中(我正在片段中工作):
db = FirebaseFirestore.getInstance();
queryAllProjects();
recyclerView.setAdapter(new ProjectRecyclerViewAdapter(projects, ...
...
private void queryAllProjects() {
projects = new ArrayList<>();
//I've already tried to make a local list and return that, however,
//the compiler would force me to declare the list as final here, and it wouldn't solve anything.
db.collection("projects")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
Project project = document.toObject(Project.class);
projects.add(project);
}
Log.d(TAG, "After for loop: " + projects.toString());
//Here the list is OK. Filled with projects.
//I'd like to save the state of the list from here
} else {
Log.d(TAG, "Error getting document: ", task.getException());
Toast.makeText(getContext(), R.string.error, Toast.LENGTH_SHORT).show();
}
}
});
Log.d(TAG, "End of method: " + projects.toString());
//Oddly enough, this log displays before the other logs.
//Also, the list is empty here, which is probably what I'm unintentionally feeding into the Recycler View's adapter
}
这是我一直关注的官方文档
https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects
【问题讨论】:
-
添加到适配器后是否调用了notifyDataSetChange
-
好吧,在这种情况下,项目列表在设置适配器之前更改,而不是之后。所以应该没有必要通知它。 (刚刚用 onCreateView 中的内容更新了帖子)。或者,我尝试设置一个带有空列表的适配器,然后调用我的查询方法,然后通知。但结果相同。
标签: java android firebase google-cloud-firestore