首页 > 解决方案 > 为什么我一直抛出 NullPointerException?

问题描述

我正在尝试将活动用户信息加载到新活动中并显示它。我在不同的活动中做过类似的事情,而且效果很好,但由于某种原因,事实并非如此,我不确定。每当 android studio 尝试调用用户的方法时,它都会抛出 NullPointerException。

我已经尝试了我能想到的一切,重新格式化它的编写方式,以不同的方法嵌套,以不同的方式将数据传递给它。没有任何效果,我在该主题上找到的每篇文章都没有帮助

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_edit);
    int userID = getIntent().getIntExtra("sessionUser", 0);
    tuckBoxDao = TuckBoxDB.createTuckBoxDB(this).tbDao();

    Email = findViewById(R.id.email);
    Username = findViewById(R.id.username);
    Password = findViewById(R.id.password);
    Mobile = findViewById(R.id.phoneNumber);
    Notifications = findViewById(R.id.notificationBox);
    Emails = findViewById(R.id.emailBox);
    registerButton = findViewById(R.id.registerButton);
    registerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            registerUser(user);
        }
    });

    backButton = findViewById(R.id.backButton);
    backButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            goBack();
        }
    });

    user = LoginActivity.tuckBoxDB.tbDao().searchById(userID);

    String username = user.getUsername();
    Username.setText(username);
    String email = user.getEmail();
    Email.setHint(email);
    String mobile = user.getMobile();
    Mobile.setHint(mobile);
    Boolean notifications = user.getNotifications();
    Notifications.setChecked(notifications);
    Boolean emails = user.getEmails();
    Emails.setChecked(emails);

}

我本来希望这可以正常工作并更新和显示正确的信息,因为它在我之前制作的片段中完全做到了这一点,但是由于某种原因,它一到达 user.getUsername(); 就会抛出。

标签: javaandroidnullpointerexception

解决方案


用户为空。检查 null 如下

if(user != null){
String username = user.getUsername();
Username.setText(username);
String email = user.getEmail();
Email.setHint(email);
String mobile = user.getMobile();
Mobile.setHint(mobile);
Boolean notifications = user.getNotifications();
Notifications.setChecked(notifications);
Boolean emails = user.getEmails();
Emails.setChecked(emails);
}

推荐阅读