从具有许多节点的firebase数据库中检索数据

时间:2017-09-17 15:22:53

标签: java android firebase firebase-realtime-database

enter image description here

如何从这些节点获取数据?

这里我有2个父母资产和负债,每个人都有自己的子女(例如:cash_at_bank,股票等等),我想从这些孩子中获取每个孩子的数据。多个数据。

  1. 首先我使用地图,但现在我无法使用它,因为我无法确定有多少孩子,我有cash_at_bank或cash_in_hand等。
  2. 一旦我从每个节点获得时间,我如何将其格式化为用户可读

1 个答案:

答案 0 :(得分:0)

我建议你不要将“time:value_here”添加为“时间”的孩子,而是直接添加“time:value_here”作为“cash_at_bank”的直接子项,这将使您的阅读操作更容易:< / p>

root/
|___ ASSETS/
|      |___ Cash_at_bank
|               |___ ID1
|                       |___ time : 1223724673
|                       |___ value : 456
|               |___ ID2
|                       |___ time : 1333768287
|                       |___ value : 789
|               ...

现在,如果您想访问Cash_at_bank数据,可以这样做:

let cashAtBankRef = Database.database().reference().child("ASSETS").child("Cash_at_bank")

cashAtBankRef.observeSingleEvent(of: .value, with: { (snapshot) in

            // Iterate through all the children :

            for child in snapshot.children.allObjects as! [DataSnapshot] {

                 // Get the time and the value for each child :

                 guard let time = child.childSnapshot(forPath: "time").value as? NSNumber else {
                       return
                 }

                 guard let valueString = child.childSnapshot(forPath: "value").value as? String else {
                       return
                 }

                 // ...Do something with your data here (store it in an array, etc...)

            }

 })

注意:当然您可以用完全相同的方式访问Cash_in_Hand数据,但只是更改数据库引用:

let cashInHandRef = Database.database().reference().child("ASSETS").child("Cash_in_Hand")

更新:既然你问过我,请问你在Java中如何做到这一点:

// Add your observer

FirebaseDatabase.getInstance().getReference().child("ASSETS").child("Cash_in_Hand").addListenerForSingleValueEvent(new ValueEventListener() {
         @Override
         public void onDataChange(DataSnapshot dataSnapshot) {

          // Iterate through all the children:

          for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {

                    // Access your values here
            }
        }
        @Override
         public void onCancelled(DatabaseError error) {
          }
   });
相关问题