我得到以下异常
java.lang.NumberFormatException:无效的整数:“”
当您尝试将值存储到共享首选项中而输入字段中尚未插入任何内容时,就会发生这种情况。这是因为我将输入解析为 int (因为我需要对数字进行减法)
这不是什么大问题,因为应用程序可以工作,但是以防万一使用该应用程序的人想要变得奇怪并尝试按保存按钮而不输入任何我不希望它插入的数据。
我已经尝试过以下方法:
else if (obj ==null || obj.currentWeight.contains("")||obj.targetWeight.contains("")){
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("No Data Stored");
builder.setMessage("Please insert your target weight and your current weight and click Store Weight")
.setPositiveButton("OK", null).show();
从我可以看出,如果我将上述声明保留为
else if (obj ==null){
那么如果插入空值,对话框将打开并显示一条消息。
我收到数字格式异常。
任何帮助,将不胜感激
一般来说,异常处理是处理这种不良行为的好方法:
if( obj != null && obj.getTargetWeight() != null ) {
try {
int i = Integer.parseInt( obj.getTargetWeight() );
//do something if target weight is a number
} catch( NumberFormatException ex ) {
//do something if target weight was not a number.
}
}
---编辑为精确的异常类型
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)