How to Traverse a Firebase Structure in Android?

后端 未结 2 1546
长发绾君心
长发绾君心 2021-01-16 22:14

I need to traverse the Firebase schema to get data for each workouts & display it in a RecyclerView. Now I can\'t traverse the Schema in the Firebase using

相关标签:
2条回答
  • 2021-01-16 22:22

    As @ReazMurshed said, you're almost there. But you're failing to iterate over one level in your tree. It seems that ref is pointing to the subscriptions node in your JSON. Under that you have users and then you have the push ids. So you'll need to do a double loop:

    ref.addListenerForSingleValueEvent(new ValueEventListener) {
      public void onDataChange(DataSnapshot snapshot) {
        if (dataSnapshot.exists()) {
          for (DataSnapshot userSnapshot : snapshot.getChildren()) {
            for (DataSnapshot programSnapshot : userSnapshot.getChildren()) {
              Program program = programSnapshot.getValue(Program.class);
          }
        }
      }
    
      public void onCancelled(FirebaseError firebaseError) {
    
      }
    });
    
    0 讨论(0)
  • 2021-01-16 22:32

    You're almost there. You just need to add addListenerForSingleValueEvent listener with your reference to iterate through the data associated with the reference node. Here's an example of how it could be done.

    In your case, lets just declare a class named ProgramList

    public class ProgramList {
        public List<Program> mProgramList;
    }
    

    Now get reference to the to the email address node and add a listener to it.

    ref.addListenerForSingleValueEvent(new ValueEventListener) {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot programSnapshot : dataSnapshot.getChildren()) {
                    final ProgramList mProgramList = programSnapshot.getValue(ProgramList.class);
    
                    // Now iterate through the list here. 
                }
            }
        }
    
        @Override
        public void onCancelled(FirebaseError firebaseError) {
    
        }
    });
    

    You might check the firebase documentation for retrieving data in android again. This is an example of a same database structure like you have here.

    0 讨论(0)
提交回复
热议问题