Android Firebase获取所有用户信息问题

时间:2018-10-01 15:33:55

标签: java android firebase

我想列出注册系统的用户。

主页:

    List<User> users;
    databaseReference = FirebaseDatabase.getInstance().getReference("Users");

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists())
            {
                for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
                {
                    User user = postSnapShot.getValue(User.class);
                    users.add(user);
                    customAdapter.notifyDataSetChanged();

                }
            }

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("selam", "onCancelled: " + databaseError );
        }
    });

用户Java类

public class User {


private String email ="";
private String nickname="";
private String status="";
private String uid="";


public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getNickname() {
    return nickname;
}

public void setNickname(String nickname) {
    this.nickname = nickname;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

İmages

1 个答案:

答案 0 :(得分:0)

您得到了NullPointerException,因为您尚未初始化users列表。要解决此问题,请使用以下代码:

databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists())
        {
            List<User> users = new ArrayList<>(); //Initialize the list
            for(DataSnapshot postSnapShot : dataSnapshot.getChildren())
            {
                User user = postSnapShot.child("userInfo").getValue(User.class);
                users.add(user);

            }
            customAdapter.notifyDataSetChanged();
        }

    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e("selam", "onCancelled: " + databaseError );
    }
});

请注意,我将customAdapter.notifyDataSetChanged();移到了for循环之外,并且我还添加了.child("userInfo")调用,因为您的数据库树中有一个额外的级别。