【问题标题】:android number format exceptionandroid数字格式异常
【发布时间】:2012-04-11 10:34:07
【问题描述】:

我得到以下异常

java.lang.NumberFormatException: Invalid 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){

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

我得到数字格式异常。

任何帮助将不胜感激

【问题讨论】:

  • 这里有什么 targetWeight..?
  • targetweight 和当前权重是 int 来自编辑文本 int targetWeight = Integer.parseInt(obj.targetWeight);
  • 这一行是你的问题:targetWeight 可以为空或为空
  • 是的。我知道这是问题所在,但我该如何解决这个问题?

标签: android android-dialog numberformatexception


【解决方案1】:

一般来说,异常处理是处理这种不良行为的好方法:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2015-12-31
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多