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

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

问题描述

一个很好的例子。

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.

Here's my code

@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();
    }
}

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?

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}.. }

解决方案

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());
        }
    });

A few things to note here:

  • 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天全站免登陆