有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在安卓(Java)中从Firestore读取嵌套对象值及其键

我试图从安卓中的嵌套对象中读取值以及这些键,但我无法根据我的要求找到任何解决方案。(我是firestore和安卓开发的新手)

{img1}$


我尝试了foreach循环,但它显示错误-foreach不适用于“java”类型。util。地图':-

for(DocumentSnapshot ds: document.getData())

于是我尝试了这个:-

Map<String, Object> myMap = (Map<String, Object>) document.getData();
String name = ""; //don't know how to get key i.e(clamp,gear) as i can't pass all of them.
String url = (String) myMap.get("url");//url returns null

这是我的代码:-

FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection("categoryType").document("Hardware");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        Log.d(TAG, "DocumentSnapshot data: " + document.getData());//see log below
                        Map<String, Object> myMap = (Map<String, Object>) document.getData();
                        String name = "";
                        String url = (String) myMap.get("url");
                        ItemCategory category = new ItemCategory(name,url);
                        itemCategoryList.add(category);
                    } else {
                        Log.d(TAG, "No such document");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
                itemCategoryAdapter.notifyDataSetChanged();
            }
        });


记录。d打印此文件:-
{Hammer={url=https://someURL}, Nail={url=https://someURL}, Shovel={url=https://someURL}}

总之,我想要的是:-
name=“Hammer”
url=“someUrl”

name=“Nail”
url=“someurl”


共 (2) 个答案

  1. # 1 楼答案

    我知道为时已晚,但对其他人有帮助

    如果要动态获取字段名,请创建一个数组并将所有字段名添加到该数组中,也可以在添加新数据时将其字段名添加到该数组中

    现在,使用这个数组,您可以创建一个for循环来获取所有字段

  2. # 2 楼答案

    首先,您必须获取钳形映射,然后使用该映射获取其url属性。这是伪代码,不是完整代码,但说明了您需要做什么。为简洁起见,地图上缺少泛型:

    // get the document data map from the snapshot
    Map data = snapshot.getData();
    // get the Clamp field, which is an object field, so it will arrive as a Map
    Map clamp = (Map) data.get("Clamp");
    // get the String value of the url property on the object
    String url = (String) clamp.get("url");