如何在Firebase数据库中获取所有嵌套的子数据?

时间:2017-02-13 07:51:24

标签: android firebase firebase-realtime-database

我在下面有一个Firebase数据库结构。如何获得room_name_public的值?我想检索所有这些值并在列表视图中显示它。此处,55aqdTkLPrMwB6H0KX4Z0RUe6s52是Firebase用户ID,-KcqR5Db5BidD0XpQ1z1功能创建了push()

enter image description here

1 个答案:

答案 0 :(得分:4)

好的,你可以这样试试。

创建一个普通对象,如下所示:

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;
    }
}

接下来,在您的活动或片段中,声明并定义监听器:

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

我认为mFirebaseDatabaseReferencepublic_rooms节点的firebase引用。 yourList是一个字符串ArrayList,连接到适配器以进行列表视图。

希望这有帮助

<强>更新

如果您想获取用户的房间,了解userId,您必须以这种方式编辑以前的方法:

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