【问题标题】:My app crashes android studio when no value is plugged in by User当用户没有插入任何值时,我的应用程序崩溃了 android studio
【发布时间】:2018-03-15 22:33:14
【问题描述】:

我正在尝试使用 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.");

【问题讨论】:

  • 省去我们的猜测工作,然后将错误消息发布到您的 logcat 中。
  • 为了以后的参考你必须知道像这样的一行代码 :: Double.parseDouble(editText.getText().toString()); 并不是很容易调试。

标签: android crash try-catch


【解决方案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) {

     ...

【讨论】:

    【解决方案2】:

    我宁愿检查当用户按下按钮时 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) {
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多