如果值为NULL,则显示错误消息;如果EditText为空但是应用程序不断崩溃,则显示错误消息

时间:2018-04-23 06:49:29

标签: java android crash

public void add(View v)
{

    EditText first=findViewById(R.id.first),second=findViewById(R.id.second);
    double f=Double.parseDouble(first.getText().toString());
    double s=Double.parseDouble(second.getText().toString());
    TextView result=findViewById(R.id.result);
    double r;
    if(TextUtils.isEmpty(first.getText().toString()))
    {
        first.setError("This field can't be empty");
    }
    else if(TextUtils.isEmpty(second.getText().toString()))
    {
        second.setError("This field can't be empty");
    }
    else {
        r = f + s;
        result.setText("" + r);
    }

}

如果editText为空,我想从用户输入两个数字并显示错误信息 但是在执行这段代码时,我的应用程序一直在崩溃。

3 个答案:

答案 0 :(得分:3)

如果Editext值不为空,则需要将Double值转换为Editext

试试这个

public void add(View v)
{

    EditText first=findViewById(R.id.first);
    EditText second=findViewById(R.id.second);      

    TextView result=findViewById(R.id.result);

    double r;

    if(TextUtils.isEmpty(first.getText().toString()))
    {
        first.setError("This field can't be empty");
    }
    else if(TextUtils.isEmpty(second.getText().toString()))
    {
        second.setError("This field can't be empty");
    }
    else {
        double s=Double.parseDouble(second.getText().toString());
        double f=Double.parseDouble(first.getText().toString());
        r = f + s;
        result.setText("" + r);
    }

}

答案 1 :(得分:3)

全球宣布第二名

public void add(View v) {
    first = findViewById(R.id.first);
    second = findViewById(R.id.second);
    TextView result = findViewById(R.id.result);
    double r;
    if (Validates()) {
        double s = Double.parseDouble(second.getText().toString());
        double f = Double.parseDouble(first.getText().toString());
        r = f + s;
        result.setText("" + r);
    }
}


public boolean Validates() {
    if (first.getText().toString().equalsIgnoreCase("")) {
        first.setError("This field can't be empty");
        return false;
    } else if (second.getText().toString().equalsIgnoreCase("")) {
        second.setError("This field can't be empty");
        return false;
    } else {
        return true;
    }
}

答案 2 :(得分:1)

  1. 在空检查之前添加“null”检查
  2. 例如:

    if((first.gettext().toString) == null ||
        TextUtils.isEmpty(first.getText().toString()))
            {
                first.setError("This field can't be empty");
            }
            else if((second.gettext().toString) == null || TextUtils.isEmpty(second.getText().toString()))
            {
                second.setError("This field can't be empty");
            }
            else {
                r = f + s;
                result.setText("" + r);
            }