【问题标题】:java.lang.NullPointerException getDouble [duplicate]java.lang.NullPointerException getDouble [重复]
【发布时间】:2017-11-27 13:45:42
【问题描述】:

如何将此代码 sn-p 重写为不产生 java.lang.NullPointerException 的形式?

Intent bank_Amount_Intent = getIntent();
Bundle bundle = bank_Amount_Intent.getExtras();
double buyin_Money = bundle.getDouble("buyin", 0);
total = buyin_Money;
bank_Amount.setText(String.valueOf(currency_Format.format(buyin_Money)));

【问题讨论】:

  • 在尝试访问其成员之前实例化变量,或添加空检查

标签: java android nullpointerexception


【解决方案1】:

嗯,我会根据显示的少量代码进行推测。由于currency_Format 仅显示正在使用我假设您已成功实例化它,因此这不是异常的来源。

只剩下 bank_Amount_Intent 和 bundle。

虽然 getIntent 可能会在某些极端情况下返回 null,但我的赌注是在 bundle 上,你假设意图有一个 Bundle 并且可能是你的空指针所在的位置。

试试double buyin_Money = bundle == null ? 0: bundle.getDouble("buyin", 0);

首先检查捆绑包是否为空,如果它实际上为空,则为变量设置 0 值。

【讨论】:

    【解决方案2】:

    你首先需要确定哪个变量是空的,所以使用调试器或者像这样继续:

    public int yourFunction(){
        Intent bank_Amount_Intent = getIntent();
        if (bank_Amount_Intent == null) {
            System.out.println("bank_Amount_Intent is null");
            return -1; //error #1
        }
    
        Bundle bundle = bank_Amount_Intent.getExtras();
        if (bundle == null) {
            System.out.println("bundle is null");
            return -2; //error #2
        }
    
        double buyin_Money = bundle.getDouble("buyin", 0);
        total = buyin_Money; // assuming "total" also is a double
        bank_Amount.setText(String.valueOf(currency_Format.format(buyin_Money)));
        return 0; //no error
    }
    

    然后您可以在控制台中看到哪个值为 null。您还可以使用返回值来确定该函数的错误代码。

    当你知道哪个值为空时,你可以做两件事:评估你是否想保持它为空

    如果您同意在该方法中保留空值,则可以使用它来弹出错误或您可能想要对空值执行的任何操作

    如果您不想要空值,您可以创建所需类型的对象的实例。例如,如果bundle 为空,您可以这样做:bundle = new Bundle();。或者,您最好首先检查为什么该值为 null 并更正错误。有可能其他函数返回 null,而您在执行过程中只会得到 NullPointerException。

    【讨论】:

      【解决方案3】:
      try{
            Intent bank_Amount_Intent = getIntent();
              Bundle bundle = bank_Amount_Intent.getExtras();
              double buyin_Money = bundle.getDouble("buyin", 0);
              total = buyin_Money;
              bank_Amount.setText(String.valueOf(currency_Format.format(buyin_Money)));
      }
      catch(Exception e)
      {
      e.printStackTrace();
      }
      

      这不会产生任何异常,但如果您尝试处理空对象,那么您将无法获得任何结果。

      编码愉快!!

      【讨论】:

      • 前 3 次有效,但现在又出现了错误...
      • 你能发布错误吗??
      • java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.chan.blackjack/com.example.chan.blackjack.MainActivity}:java.lang.NullPointerException:尝试调用虚拟方法'java.lang.String java.lang.String.trim()' 在空对象引用上
      • 这个错误不是来自你发布的代码。
      • 但这可以确定您正在操作空字符串。检查您使用 trim() 方法的代码。
      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多