简体   繁体   中英

Retrieve data from Firebase. AddValueEventListener for complex object

I am trying to use JAVA to read data from a Firebase database in an Android. I have a the following database:

{
  "info" : {
    "about" : "...........",
    "address" : "...........",
    "bus" : "",
    "contact" : "........",
    "email" : ".........",
    "mobile_phone" : ".........",
    "trolley" : ""
  },
  "schedule" : {
    "47" : {
      "hall" : {
        "id" : 2,
        "name" : "..."
      },
      "presentation" : {
        "about" : "",
        "id" : 1,
        "title" : "....."
      },
      "section" : {
        "id" : 2,
        "name" : ".... "
      },
      "speakers" : [ 101 ],
      "time_end" : 0,
      "time_start" : 1416652800,
      "url" : "......"
    }
  }
}

I can read simple structures, such as:

ref.child("info").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

       Info msg =dataSnapshot.getValue(Info.class);
       System.out.println(msg.getEmail());  
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

But I don't know how to retrieve data from a structure "schedule". I tried to recreate POJO and read the structure, however it's not working.

ref.child( "schedule" ).addValueEventListener( new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for ( DataSnapshot postSnapshot : dataSnapshot.getChildren() ) {
            Schedule msg = dataSnapshot.getValue( Schedule.class );
            System.out.println( msg.getHall().getId() );
        }


    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }


} );

Small error, just change dataSnapshot to postSnapshot inside the for looping and you're good to go.

for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
    Schedule msg = postSnapshot.getValue(Schedule.class);
    System.out.println(msg.getHall().getId());
}

If the problem still there, then it's your POJO.

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