如何在Realtime Firebase数据库中获取子节点和父节点的值

时间:2018-01-23 12:43:19

标签: android json firebase-realtime-database

在Realtime Firebase数据库中获取子节点键值对很容易,但是如何获取子节点的父节点的键。

{
  "Neeraj":
  {
    "January": 
    {
      "2018-01-22":
      {
        "inStatus": "1",
        "inTime": "11:58:12 pm",
        "outSatus": "1",
        "outTime": "11:58:12 pm"
      }
    }
  }
}

以下图片是Firebase实时数据库的结构

enter image description here

1 个答案:

答案 0 :(得分:1)

假设Neeraj节点是Firebase-root的直接子节点,要获取该数据,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dateRef = rootRef.child("Neeraj").child("January").child("2018-01-22");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String inStatus = dataSnapshot.child("inStatus").getValue(String.class);
        String inTime = dataSnapshot.child("inTime").getValue(String.class);
        String outSatus = dataSnapshot.child("outSatus").getValue(String.class);
        String outTime = dataSnapshot.child("outTime").getValue(String.class);
        Log.d("TAG", "Neeraj" + " / " + dataSnapshot.getRef().getParent().getKey() + " / " + dataSnapshot.getKey());
        Log.d("TAG", inStatus + " / " + inTime + " / " + outSatus + " / " + outTime);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
dateRef.addListenerForSingleValueEvent(eventListener);

您的输出将是:

1 / 11:58:12 pm / 1 / 11:58:12 pm