导致Null指针异常

时间:2016-04-05 16:23:17

标签: java android

当setText在edittext中出现值时导致错误。 Id Given是正确的,如果我给set尝试在空对象引用上调用虚方法'void android.widget.EditText.setText(java.lang.CharSequence)'

下面给出的代码我不能使用setText Otp Code“otpcode.setText(”12345“);”在oncreate它完美地工作。 当我用方法“recivedSms”给它时。它没有用。

public class Change_Password_Activity extends AppCompatActivity {
EditText user_name,pass_wd;
public   EditText otpcode;
private Button btn_submit;
private String username,otp,password;
private ProgressDialog prgDialog;
private Typeface typeface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_change__password_);
    typeface = GlobalVariables.getTypeface(Change_Password_Activity.this);
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage("Please wait...");
    // Set Cancelable as False
    prgDialog.setCancelable(false);

    otpcode = (EditText)findViewById(R.id.otpedittext);
    user_name = (EditText) findViewById(R.id.edittext_ch_user);
    pass_wd = (EditText) findViewById(R.id.edittext_ch_passwd);
    btn_submit = (Button) findViewById(R.id.button_changepswd);
    otpcode.setTypeface(typeface);
    user_name.setTypeface(typeface);
    pass_wd.setTypeface(typeface);
    btn_submit.setTypeface(typeface);



}
public void recivedSms(String message)
{
    try
    {
        int smsnumbr= Integer.parseInt(message);
        otpcode.setText(smsnumbr);

    }
    catch (Exception e)
    {
        Log.e("error", String.valueOf(e));
    }

1 个答案:

答案 0 :(得分:0)

如果你试图将smsnumbr设置为edittext,那么它将给出空指针异常,因为在setText(整数)中,android尝试从给定整数作为id的R.java文件中查找资源。要实现你想要的,你应该使用String.valueOf(..)代替。

int smsnumbr= Integer.parseInt(message);
otpcode.setText(String.valueOf(smsnumb));