Android Studio中EditText为空或值为0时Toast弹出异常求助
问题根源分析
你遇到的崩溃问题其实很明确:你在检查输入是否为空之前,就已经尝试把EditText的内容转换成Double类型了。当体重EditText为空时,Double.valueOf(editTextWeightInput.getText().toString())这行代码会抛出NumberFormatException(空字符串无法转成数字),直接导致应用崩溃,根本没机会执行后面的Toast提示逻辑。而HeightInput=0时能正常工作,是因为你输入了数字0(不是空),转换步骤没问题,能走到判断逻辑里。
解决方案
我们需要调整代码顺序,先做输入合法性检查,确认没问题后再进行类型转换和计算,同时优化判断逻辑让它更健壮:
修改后的onClick代码片段
buttonCalculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 先获取输入控件实例 EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput); EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput); // 获取输入字符串并去除首尾空格(避免用户只输入空格的无效情况) String weightStr = editTextWeightInput.getText().toString().trim(); String heightStr = editTextHeightInput.getText().toString().trim(); // 第一步:检查输入是否为空 if (TextUtils.isEmpty(weightStr) || TextUtils.isEmpty(heightStr)) { Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show(); return; // 直接返回,不执行后续逻辑 } double WeightInput; double HeightInput; try { // 尝试转换为数字,处理用户输入非数字的情况 WeightInput = Double.valueOf(weightStr); HeightInput = Double.valueOf(heightStr); } catch (NumberFormatException e) { Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show(); return; } // 检查身高是否≤0 if (HeightInput <= 0) { Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show(); return; } // 以下是原有的单位转换和BMI计算逻辑,保持不变 String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem()); String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem()); double constantWeight; double constantHeight; // 体重转换系数 if (finalWeightUnit.equals("kilograms")) { constantWeight = 1.00; } else { constantWeight = 1 / 2.204623; } // 身高转换系数 switch (finalHeightUnit) { case "inches": constantHeight = 0.0254; break; case "centimeters": constantHeight = 0.01; break; case "feet": constantHeight = 1 / 3.2808; break; default: constantHeight = 1.00; break; } // 执行BMI计算并展示结果 double finalheight = Math.pow((HeightInput * constantHeight), 2.00); double BodyMassIndex = (WeightInput * constantWeight) / finalheight; DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##"); TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult); textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex)); } });
关键修改点说明
- 调整执行顺序:先获取输入字符串并做空判断,确认非空后再尝试转换为Double,从根源避免空字符串导致的异常。
- 使用
TextUtils.isEmpty():比直接判断length() == 0更健壮,它会同时处理null和空字符串的情况,配合trim()还能过滤用户只输入空格的无效输入。 - 捕获
NumberFormatException:处理用户输入非数字(比如字母、符号)的情况,避免应用崩溃,同时弹出错误提示。 - 拆分判断逻辑:把空判断、数字转换、身高≤0的判断分开,代码更清晰,确保每种异常情况都能触发Toast提示。
这样修改后,无论是体重/身高为空、输入非数字,还是身高≤0的情况,都会正常弹出错误Toast,不会导致应用崩溃,计算逻辑也能正常运行。
内容的提问来源于stack exchange,提问作者joanshepard10
相关产品推荐
相关产品推荐

