java - 为什么我一直抛出 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(); 就会抛出。
解决方案
用户为空。检查 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);
}
推荐阅读
- python - Discord - 从 id 获取用户的服务器昵称
- c# - 尝试通过列表 C# 迭代时删除项目时的无限循环
- node.js - Nodejs应用程序构建和重新加载无法使用ansible
- powerbi - 在 Power BI 服务报表中找不到用于对可视化进行排序的排序选项
- c++ - 使用 ID2D1Device3 的 direct2d 快速入门
- c++ - 为什么不是 jthread::get_stop_source const?
- jquery - Graphileon 代理功能问题
- flutter - 我希望我的身体在 Flutter 中可以滚动
- python - 如何创建一个网站,支持目前在 R 中实施的新的文献计量方法?
- environment-variables - 无法为 gatsby 构建使用自定义环境文件