如何获取父节点的值作为字符串? [英] How to get value of parent node as string?

查看:26
本文介绍了如何获取父节点的值作为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在上面的数据结构中,我想得到值Aprilia Caponord 1200(如图所示).我有对 Aprilia(根节点)的 Firebase 引用,我可以获得所有的键/值对数据.

So in the above data structure, I want to get value Aprilia Caponord 1200 (marked in fig.). I have Firebase reference to Aprilia (root node) and I can get all the key/value pair data.

这是我的代码

@override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChild()) {
    Map<?, ?> value = (Map<?, ?>) child.getValue();
    String bike_price = value.get("price").toString();
    String image_url = value.get("image_url").toString();
    }
}

很明显,我可以获得具有键/值关系的子节点的所有值.但是我无法具体获取父节点的名称.那么如何以String格式获取父节点的值呢?

So clearly I can get all the values of child nodes having key/value relations. But I can't specifically get the name of the parent node. So how can I get the value of parent node in String format?

如果我打印 child.getValue().toString(),我会得到 JSON 值,但我对解析 JSON 不感兴趣.有没有什么具体的方法可以获取父节点的值?

If I print child.getValue().toString(), I get JSON value, but I am not interested in parsing JSON. Is there any specific way to get parent node value?

{Aprilia Caponord 1200={image_url=____________, price=18.35}.. }

推荐答案

您可能正在寻找 DataSnapshot 上的 getKey() 方法:

You're probably looking for the getKey() method on DataSnapshot:

    mFirebaseRef = new Firebase("https://yours.firebaseio.com");
    mFirebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot child: dataSnapshot.getChildren()) {
                Log.i("MainActivity", child.getKey());
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.e("MainActivity", "onCancelled", firebaseError.toException());
        }
    });

这里有几点需要注意:

  • 我将您代码中的 getChild() 更改为 getChildren(),因为我知道没有方法 getChild()
  • 您应该考虑使用addChildEventListener,它为您在较低级别的节点上提供DataSnapshots
  • 如果您为汽车创建包装类",事情会变得容易得多.然后,适用于 Android 的 Firebase SDK 会自动将 JSON 解包到该类的实例中.请参阅我们的 AndroidChat 存储库,了解一个很好的例子.
  • I changed getChild() in your code to getChildren(), since there is not method getChild() that I'm aware of.
  • You should consider using addChildEventListener, which gives you DataSnapshots on the lower-level nodes
  • Things will get considerably easier if you create "wrapper classes" for your cars. The Firebase SDK for Android will then automagically unwrap the JSON into instances of that class. See our AndroidChat repo for a good example of this.

这篇关于如何获取父节点的值作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆