You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EditText为空时显示错误提示却遇应用崩溃,求Android开发解决方案

解决EditText为空时应用崩溃的问题

嘿,我一眼就看出问题出在哪了!你的代码逻辑顺序完全搞反啦~

你现在是先把EditText的内容直接转成double,之后才去判断输入是否为空。如果输入框是空的,first.getText().toString()会返回空字符串,这时候调用Double.parseDouble()会直接抛出NumberFormatException,程序直接崩溃,根本走不到后面的错误提示代码。

修复步骤:

  • 先获取输入的字符串,优先判断是否为空
  • 还要处理用户输入非数字内容的情况(比如字母、符号),避免同样抛出异常崩溃
  • 只有当所有输入都合法时,再执行计算逻辑

修复后的完整代码:

public void add(View v) {
    EditText first = findViewById(R.id.first);
    EditText second = findViewById(R.id.second);
    TextView result = findViewById(R.id.result);
    
    // 获取输入并去除首尾空格(避免只输入空格被当成有效内容)
    String firstInput = first.getText().toString().trim();
    String secondInput = second.getText().toString().trim();
    
    boolean hasError = false; // 标记是否存在输入错误

    // 检查第一个输入框
    if (TextUtils.isEmpty(firstInput)) {
        first.setError("This field can't be empty");
        hasError = true;
    } else {
        // 尝试转换为数字,捕获非数字输入的异常
        try {
            Double.parseDouble(firstInput);
        } catch (NumberFormatException e) {
            first.setError("Please enter a valid number");
            hasError = true;
        }
    }

    // 检查第二个输入框
    if (TextUtils.isEmpty(secondInput)) {
        second.setError("This field can't be empty");
        hasError = true;
    } else {
        try {
            Double.parseDouble(secondInput);
        } catch (NumberFormatException e) {
            second.setError("Please enter a valid number");
            hasError = true;
        }
    }

    // 没有错误时执行计算
    if (!hasError) {
        double f = Double.parseDouble(firstInput);
        double s = Double.parseDouble(secondInput);
        double r = f + s;
        result.setText(String.valueOf(r));
    }
}

额外说明:

  • 用trim()处理输入是为了过滤掉用户只输入空格的情况,这种场景也应该视为空输入
  • 加入try-catch块可以处理非数字输入的异常,让程序更健壮,同时给用户明确的错误提示
  • 先一次性检查所有输入错误,再执行计算,这样多个输入框有问题时可以同时显示错误提示,用户体验更好

内容的提问来源于stack exchange,提问作者Vivank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:58:36