简体   繁体   English

如何从android的fireStore数据库中读取嵌套地图

[英]How to read the nested maps from fireStore database from android

在此处输入图片说明

In the above image, I have a map that contains an arrays list of 2020, 2021, etc. I want to display the arrays data in RecyclerView.在上图中,我有一张地图,其中包含 2020、2021 等的数组列表。我想在 RecyclerView 中显示数组数据。 How to do that in android?如何在android中做到这一点?

Also how to retrieve data if a map contains a list of maps.如果地图包含地图列表,也如何检索数据。 I'm able to get the documents with field names, but struggling with how to get maps with field names and data in that maps.我能够获取带有字段名称的文档,但在如何获取带有字段名称和数据的地图方面苦苦挣扎。

DocumentSnapshot's getData() method, returns an object of type Map<String, Object> . DocumentSnapshot 的getData()方法返回一个Map<String, Object>类型的Map<String, Object> Since it's a Map, we can simply get the year and then iterate through the corresponding URLs, like in the following lines of code:由于它是一个 Map,我们可以简单地获取year ,然后遍历相应的 URL,如下面的代码行所示:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference subjectRef = rootRef.collection("subject");
DocumentReference politicalScienceRef = subjectRef.document("political science");
politicalScienceRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                List<String> urls = new ArrayList<>();
                Map<String, Object> data = document.getData();
                Map<String, Object> year = (Map<String, Object>) data.get("year");
                for (Map.Entry<String, Object> entry : year.entrySet()) {
                    List<String> yearUrls = (List<String>) entry.getValue();
                    for (String url : yearUrls) {
                        urls.add(url);
                    }
                }
                for (String url : urls) {
                    Log.d("TAG", url);
                }
            } else {
                Log.d("TAG", "No such document");
            }
        } else {
            Log.d("TAG", "get failed with ", task.getException());
        }
    }
});

In the end, simply pass the urls list to an adapter, and display all those URLs into a RecyclerView.最后,只需将urls列表传递给适配器,并将所有这些 URL 显示到 RecyclerView 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM