MyNameIsAsker MyNameIsAsker - 2 months ago 16
Android Question

Android - Firebase Database accessing to sub directory

This is my database in the firebase

{
"Rooms" : {
"room1" : {
"Header" : {
"Recipient" : "JZrMZeE6JXYULHRtDbksfagnQE53",
"Sender" : "fD0E2IbeGub53n1muYSYX88N6US2"
},
"Message" : {
"MESSAGE-QWEASD" : {
"Message" : "Hello World",
"Name" : "fD0E2IbeGub53n1muYSYX88N6US2"
}
}
}
}
}


When i see the guide of firebase's database, it always requires a specified location to access data. However, I want to access sub directory(room1) of the main directory(Rooms) without indicating its name. For now, I need to indicate the name to access the data inside its name of room.

dataSnapshot.child("Rooms").child("room1").getValue().toString()


Is there a method that returns a string of sub directory's name

Answer

If you want to access Rooms, you need to create Rooms object like your nodes above. But I think you have room1, room2, room3 ... and your structure need to be like that (array list in object room to easy to parse as an Object Room). The key don't change.

{
  "Rooms" : [ 
    {
    "name" : "room1",
     {
      "Header" : {
        "Recipient" : "JZrMZeE6JXYULHRtDbksfagnQE53",
        "Sender" : "fD0E2IbeGub53n1muYSYX88N6US2"
      },
      "Message" : {
        "MESSAGE-QWEASD" : {
          "Message" : "Hello World",
          "Name" : "fD0E2IbeGub53n1muYSYX88N6US2"
        }
      }
    }
  }
  {
       "name" : "room2",
       ....
  }
  ]
}

class Room {
    String name;
    Header Header;
    Message Message;
}

class Header {
    String Recipient;
    String Sender;
}

Do the similar with Message, but I think It needs to be easily to remove MESSAGE-QWEASD, only have Message and Name to make it easily as Object.

And finally

List<Room> rooms = (List<Room>)dataSnapshot.child("Rooms").getValue();
Comments