[英]DataSnapshot's getValue method returns a null instance of my class when it shouldn't. Adding fields to my Class breaks my code
因此,首先我将显示我的代码,然后将给出有关问题情况的一些特定信息。
dbRef = database.getReference().child("Users").child(emailKey);
dbRefL = FirebaseDatabase.getInstance().getReference();
/* This executes when the Activity starts. It sets email1 to the logged in User's email add
* and it sets sellerName to the logged in User's username. Should only execute once but doesn't
* really matter if that's not true;
*/
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInfo userinfo = dataSnapshot.getValue(UserInfo.class);
email1 = userinfo.email;
sellerName = userinfo.username;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我的错误如下:
java.lang.NullPointerException:尝试从Semicolon.foodbnb.CreateListingActivity2 $ 1.onDataChange上的空对象引用中的字段'java.lang.String semicolon.foodbnb.UserInfo.email'中读取
因此,当我知道Firebase节点Users> emailKey> email不应为null时,会收到nullPointerException。
需要注意的一点是,我只是在对UserInfo clsas进行更改时才开始遇到此问题。 我不知道它应该如何影响这一点。
遍历其他Stack Overflow帖子,使我认为启动此Activity时它抓住了错误的UserInfo类。 (此侦听器位于OnCreate方法中)。
我只想访问当前登录的用户的电子邮件和用户名(“用户”>“ emailKey”>“用户名/电子邮件”下的两个字段)
这是我非常简单的UserInfo类。
public class UserInfo {
public String username;
public String email;
public String password;
public String zipcode;
public String creditcard;
public String phone;
public String profilePicture;
//No arg ctor
public UserInfo() {}
//5 arg ctor -- every field is initialized
public UserInfo(String un, String email, String pw, String zip, String cc, String phone) {
username = un;
password = pw;
this.email = email;
zipcode = zip;
creditcard = cc;
this.phone = phone;
profilePicture = "";
}
public UserInfo(String un, String email, String pw, String zip, String cc, String phone, String picture) {
username = un;
password = pw;
this.email = email;
zipcode = zip;
creditcard = cc;
this.phone = phone;
profilePicture = picture;
}
//getters
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public String getZipcode() {
return zipcode;
}
public String getCreditcard() {
return creditcard;
}
public String getPhone() {
return phone;
}
public String getProfilePicture() {
return profilePicture;
}
}
当我尝试向我的UserInfo类添加arrayList时,出现了该nullpointer问题。 现在,当我添加“个人资料图片”字段时,问题再次出现。 为什么添加的字段会破坏我的代码?
编辑:如果我使用没有配置文件“图片”字段的旧用户帐户登录,则没有nullPointer问题。 如果我使用个人资料图片字段登录到新帐户,则存在nullpointer问题
您的UserInfo模型类应与您从Firebase读取的数据相同。 如果您要向其中添加新字段,请更新Firebase数据库方案以包括新字段,它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.