当用户没有插入任何值时,我的应用程序崩溃了android studio

时间:2018-03-15 22:33:15

标签: android crash try-catch

我正在尝试使用try / catch方法来阻止应用程序在用户没有提供任何值时崩溃,即使使用此try catch,它仍然会显示错误。

提前感谢那些会回复的善良人士

    editText = (EditText) findViewById(R.id.editText);
    textView = (TextView) findViewById(R.id.textView);
}

public void btnSubmit_OnClick(View view) {

    try {
        double num = Double.parseDouble(editText.getText().toString());

    }catch (Exception e) {
         Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    if (num >= 6.5 && num < 14) {

            textView.setText("You may have Diabetes or if you are already diagnosed, have Uncontrolled Diabetes. However, I still find it best that you contact your attending physician for proper assessment. Thank you.");


        } else if (num >= 14){
            textView.setText("This is the highest level the application can read. Please contact your attending physician as either there is an error or you are suffering from a condition that warrants immediate referral. Thank you.");

2 个答案:

答案 0 :(得分:1)

只需在try-catch外面声明num即可。

double num=0.0;
try {
    num = Double.parseDouble(editText.getText().toString());
}catch (Exception e) {
    Toast.makeText(MainActivity.this, e.getMessage(), 
                 Toast.LENGTH_SHORT).show();
}

if (num >= 6.5 && num < 14) {

     ...

答案 1 :(得分:1)

我宁愿检查当用户按下按钮时EditText是否为空。

    editText = (EditText) findViewById(R.id.editText);
    textView = (TextView) findViewById(R.id.textView);
}

public void btnSubmit_OnClick(View view) {

if (editText.getText().toString() != null) {
    double num = Double.parseDouble(editText.getText().toString());

} else {
    Toast.makeText(mContext, "Fill in the field", Toast.LENGTH_SHORT).show();    
}

if (num >= 6.5 && num < 14) {
...