Eclipse开发Android应用时EditText空值检测失效导致崩溃问题求助
问题定位
- 崩溃由
NumberFormatException导致:你在validar()方法中先执行了Integer.parseInt()、Float.parseFloat()类型转换,再判断输入字符串是否为空。当输入为空时,空字符串无法转为数字,直接抛出异常,根本走不到后面的空值判断逻辑,应用就会停止运行。 - 输入0时逻辑正常是因为0是合法数字,类型转换不会报错,可以正常走到后续校验逻辑返回false。
修复方案
调整validar()方法的执行顺序:先判断输入是否为空,再执行类型转换,同时补充非法字符输入的捕获逻辑,避免用户输入非数字内容也导致崩溃,修改后的代码如下:
public boolean validar(){ boolean retorno = true; // 先获取输入值,加trim去掉前后空格,避免用户只输空格的情况 codigoS = etc.getText().toString().trim(); nombre = etn.getText().toString().trim(); generoS = etg.getText().toString().trim(); precioS = etp.getText().toString().trim(); // 第一步先做非空校验 if(codigoS.length() == 0){ etc.setError("Se requiere un codigo"); retorno = false; } if(nombre.length() == 0){ etn.setError("Se requiere un nombre"); retorno = false; } if(generoS.length() == 0){ etg.setError("Se requiere un genero"); retorno = false; } if(precioS.length() == 0){ etp.setError("Se requiere un precio"); retorno = false; } // 非空校验全部通过后,再做类型转换,同时捕获非数字输入的异常 if(retorno){ try{ codigo = Integer.parseInt(codigoS); genero = Integer.parseInt(generoS); precio = Float.parseFloat(precioS); // 再校验数值是否为0 if(codigo == 0){ etc.setError("Se requiere un codigo"); retorno = false; } if(genero == 0){ etg.setError("Se requiere un genero"); retorno = false; } if(precio == 0){ etp.setError("Se requiere un precio"); retorno = false; } }catch (NumberFormatException e){ // 处理输入不是合法数字的情况 etc.setError("请输入合法数字"); etg.setError("请输入合法数字"); etp.setError("请输入合法数字"); retorno = false; } } return retorno; }
内容的提问来源于stack exchange,提问作者Caballero Swadiano
相关产品推荐
相关产品推荐

