简体   繁体   中英

retrieving data from firebase database having many nodes

在此处输入图片说明

how can a get the data from these nodes?

Here I have 2 parents ASSETS and LIABILITIES , each having it's own children(ex:cash_at_bank,stock etc..) and I want to get the data from each of these child which in this have multiple data.

  1. First I was using Map but now I cant use it because I cant be sure how many children Ihave in cash_at_bank or cash_in_hand etc.
  2. And once I get the time from each node how can I format it to be readable by the user

I would first suggest you not to add "time : value_here" as a child of "time", but rather directly add "time : value_here" as a direct child of "cash_at_bank" which will make your read operations easier:

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

So now if you want to access your Cash_at_bank data, you could do it like this:

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

            }

 })

Note: Of course you could access the Cash_in_Hand data in the exact same way, but just changing the database reference :

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

Update: Since you asked me, here if how you would do it in 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) {
          }
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM