首页 > 解决方案 > 在 Android 中从 textbox.getText() 插入我的模型时出错

问题描述

我在Android中使用retrofit2。

我从我的活动创建UserModelAuthModel调用方法到服务器;

用户模型类

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

标签: androidandroid-studionullpointerexception

解决方案


发生错误是因为您没有UserModelAuthModel. 您已初始化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 作为参数的构造函数。


推荐阅读