Reputation: 656
I have a Firebase database structure below. How do I get the value of room_name_public
? I want to retrieve all those values and show it in a list view. Here, 55aqdTkLPrMwB6H0KX4Z0RUe6s52
is a Firebase userID and -KcqR5Db5BidD0XpQ1z1
is created by the push()
function.
Upvotes: 3
Views: 4228
Reputation: 2135
Ok, you can try in this way.
Create a plain object, like this:
public class Room {
String room_name_pucblic;
public Room() {
}
public Room(String room_name_pucblic) {
this.room_name_pucblic = room_name_pucblic;
}
public String getRoom_name_pucblic() {
return room_name_pucblic;
}
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("room_name_pucblic", room_name_pucblic);
return result;
}
}
Next, in your activity or fragment, declare and define the listener:
ValueEventListener roomsValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for ( DataSnapshot userDataSnapshot : dataSnapshot.getChildren() ) {
if (userDataSnapshot != null) {
for ( DataSnapshot roomDataSnapshot : userDataSnapshot.getChildren() ) {
Room room = roomDataSnapshot.getValue(Room.class);
yourList.add(room.getRoom_name_pucblic());
yourAdapter.notifyDataSetChanged();
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFirebaseDatabaseReference.addListenerForSingleValueEvent(roomsValueEventListener);
I suppose that mFirebaseDatabaseReference
is the firebase reference of your public_rooms
node. yourList
is an ArrayList of strings, connected to your adapter for the list view.
Hope this helps
Update
If you want to fetch user's rooms, knowing an userId, you have to edit the previous approach in this way:
ValueEventListener roomsValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for ( DataSnapshot roomDataSnapshot : dataSnapshot.getChildren() ) {
Room room = roomDataSnapshot.getValue(Room.class);
yourList.add(room.getRoom_name_pucblic());
yourAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mFirebaseDatabaseReference.child(userId).addListenerForSingleValueEvent(roomsValueEventListener);
Upvotes: 4