How to get value of parent node as string?

前端 未结 3 1089
春和景丽
春和景丽 2020-12-06 23:41

So in the above data structure, I want to get value Aprilia Caponord 1200 (marked in fig.). I have Firebase reference to Aprilia (root nod

3条回答
  •  暖寄归人
    2020-12-07 00:02

    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.

提交回复
热议问题