如何在一个列表中显示Firebase中的所有数据?

时间:2017-10-10 04:25:02

标签: android firebase firebase-realtime-database

我们正尝试在列表中显示Firebase数据库中的所有数据。到目前为止,这是我们的代码:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");

如果那里有人可以帮助我们,那就太好了!

...谢谢

2 个答案:

答案 0 :(得分:0)

DatabaseReference myRef = database.getReference("message");
    myRef.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Get map of users in datasnapshot
                    collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    //handle databaseError
                }
            });

private void collectPhoneNumbers(Map<String,Object> users)
        {

        ArrayList<String> phoneNumbers = new ArrayList<>();

        List<ItemObjectVideo> allItems = new ArrayList<ItemObjectVideo>();
        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()){

        //Get user map
        Map singleUser = (Map) entry.getValue();
        //Get phone field and append to list
        phoneNumbers.add((String)singleUser.get("url"));

        allItems.add(new ItemObjectVideo((String)singleUser.get("name")));

        }

        rcAdapter = new VideoRecyclerViewAdapter(getApplicationContext(), allItems);
        rView.setAdapter(rcAdapter);
        rcAdapter.notifyDataSetChanged();


    }

答案 1 :(得分:0)

尝试使用此代码从Firebase中的“消息”引用中获取所有项目的列表。

myRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    long count = dataSnapshot.getChildrenCount();
                    if(count != 0 ){
                        for (DataSnapshot data : dataSnapshot.getChildren()){
                            Message mesgObj =  data.getValue(Message.class);
                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

您需要使用Firebase中的字段创建Message Model类。