android - 在 Android 中从 textbox.getText() 插入我的模型时出错
问题描述
我在Android中使用retrofit2。
我从我的活动创建UserModel
并AuthModel
调用方法到服务器;
用户模型类
public class UserModel {
public String fullName;
public String about;
public String userName;
public String password;
public Date createDate;
public Date lastSeen;
public String phonenumber;
...
}
AothModel.class
public class AuthModel {
public UserModel user;
public TokenModel token;
public ErrorResponseModel errorResponse;
...
}
还有我的活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singup);
edtPhone = (EditText)findViewById(R.id.edtphone);
AuthModel authModel = new AuthModel();
authModel.user.phonenumber = edtPhone.getText().toString();
Toast.makeText(SingUpActivity.this,authModel.user.phonenumber,
Toast.LENGTH_SHORT).show();
UserModel.phonenumber
我在模型变量中设置文本并对其进行测试。
错误:
尝试写入对象引用
'java.lang.String com.mychat.models.UserModel.phonenumber'
上的字段null
解决方案
发生错误是因为您没有UserModel
在AuthModel
. 您已初始化AuthModel
,但它不会自动创建UserModel
实例。这就是为什么每当您尝试访问 中的任何属性时它都会抛出 NullPointerException UserModel
,因为它只是null
.
像这样更改您的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singup);
edtPhone=(EditText)findViewById(R.id.edtphone);
AuthModel authModel=new AuthModel();
UserModel userModel = new UserModel();
authModel.setUserModel(userModel);
authModel.user.phonenumber = edtPhone.getText().toString();
Toast.makeText(SingUpActivity.this,authModel.user.phonenumber, Toast.LENGTH_SHORT).show();
或者您可以在 AuthModel 中创建一个接受新 UserModel 作为参数的构造函数。
推荐阅读
- javascript - 函数仅在 React Native 中运行两次后才返回参数
- mysql - mysql选择连续分组的最小和最大年份
- python - 嵌套for循环以基于pandas中的2级多索引创建多个数据透视表
- php - Laravel 资源附加本地修改的属性
- javascript - 需要拆分字符串逗号分隔,包括圆括号
- mysql - 如何禁用 MySQL histignore?
- php - 从显示每个用户记录的数据库中检索数据 - Laravel
- javascript - 根据工作日数获取工作日数组
- xml - XSD 将复杂元素定义为强制但所有子元素都是可选的是否有效?
- java - 既然不推荐使用 android 命令,我应该如何在没有 android studio 的情况下创建 android 应用程序