在EditText中输入数字会使应用程序崩溃

时间:2018-10-22 10:40:28

标签: java android

private EditText editText;
private EditText editText2;
private EditText editText3;
TextView textView,textView4;
private Button button_apply;

private TextWatcher QQ = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        String q = editText.getText().toString().trim();
        String a = editText2.getText().toString().trim();
        String z = editText3.getText().toString().trim();
        button_apply.setEnabled(!q.isEmpty() && !a.isEmpty() && !z.isEmpty());
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText =  findViewById(R.id.editText);
    editText2 = findViewById(R.id.editText2);
    editText3 = findViewById(R.id.editText3);
    textView = findViewById(R.id.text_view_selected);
    textView4 = findViewById(R.id.textView4);

    editText.addTextChangedListener(QQ);
    editText2.addTextChangedListener(QQ);
    editText3.addTextChangedListener(QQ);

    Button buttonApply = findViewById(R.id.button_apply);
    buttonApply.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            int a = Integer.parseInt(String.valueOf(editText.getText()));
            int b = Integer.parseInt(String.valueOf(editText2.getText()));
            int c = Integer.parseInt(String.valueOf(editText3.getText()));
            textView.setText("Total" + (a+b+c));
            textView4.setText("Mutiply " + (a*b*c));
        }
    });

}

在放置textwatcher之前,我的应用程序运行平稳。每当我将textwatcher放到edittext中时,它都会使应用程序崩溃。而且我认为textwatcher下方的字符串q,a,z出了点问题。我正在添加textwatcher,因此必须填充edittext才能提交。

Process: com.example.locator.myapplication, PID: 5007
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setEnabled(boolean)' on a null object reference
    at com.example.locator.myapplication.MainActivity$1.onTextChanged(MainActivity.java:35)
    at android.widget.TextView.sendOnTextChanged(TextView.java:8186)
    at android.widget.TextView.handleTextChanged(TextView.java:8248)
    at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10370)
    at 

对不起,这里。这是我的Logcat中的错误。它说的是“ button_apply.setEnabled(!q.isEmpty()&&!a.isEmpty()&&!z.isEmpty());”

1 个答案:

答案 0 :(得分:2)

解决方案:请遵循以下步骤:

只需从您的Button内的下面一行中删除onCreate()

Button buttonApply = findViewById(R.id.button_apply);

然后将其更改为:

button_apply = findViewById(R.id.button_apply);

如果Button buttonApply中有onCreate(),则它仅在方法onCreate()中成为本地对象。

因此,如果从Button中删除onCreate(),它将自动采用您已经声明的全局对象。即使在TextWatcher块中,也可以在整个类中访问它。

希望这会有所帮助。