[英]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.