显示我的firebase数据库中的数据列表

时间:2018-02-12 09:15:54

标签: android firebase firebase-realtime-database

您好我正在尝试显示我在activity中输入的数据,但问题是我不知道怎么做,我迷失在数据快照上。我想尝试只显示名称和电子邮件

我的数据库 Database

到目前为止我的代码和进度

public class AdminActivity extends AppCompatActivity {
private DrawerLayout mdrawerl;
private ActionBarDrawerToggle mtoggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin);
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users");
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            collectName((Map<String,Object>)dataSnapshot.getValue());
        }
        private void collectName(Map<String, Object> value) {
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }                         
    });

我使用How to get all child's data in firebase database?

的参考

1 个答案:

答案 0 :(得分:2)

1-创建一个包含用户对象的模型类。在你的情况下,它将是

public class User {
private String email;
private String name;
private int type;

public User() {
}

public User(String email, String name, int type) {
    this.email= email;
    this.name= name;
    this.type= type;
}
}

2 - 创建一个ArrayList,其中包含User

ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<User> userList = new ArrayList();
            for (DataSnapshot child :
                            dataSnapshot.getChildren()) {
                User user = child.getValue(User.class);
                userList.add(user )
            }
           //Here you have all user you can pass ```userList``` to your method furthur
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }                         
    });

希望这会对你有所帮助。