猿问

从 Android 上的 Firebase Firestore 查询对象列表

我正在尝试创建一种从我的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();

                        }

                    }

                });


这是我一直在关注的官方文档


https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects


哈士奇WWW
浏览 159回答 2
2回答

猛跑小猪

projects.add(project);adapter.notifyDataSetChange()添加列表后调用 notifyDataSetChange()
随时随地看视频慕课网APP

相关分类

Java
我要回答