android数字格式异常

时间:2012-04-11 10:34:07

标签: android android-dialog numberformatexception

我收到以下异常

  

java.lang.NumberFormatException:无效的int:“”

当您尝试将值存储到共享首选项中而未将任何内容插入到输入字段中时,会发生这种情况。这是因为我将输入解析为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){

然后如果插入null,则对话框将打开并显示一条消息。

我得到数字格式例外。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

一般来说,异常处理是解决此类不良行为的好方法:

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.
 }
}

---编辑为精确的异常类型

相关问题