0

I am attempting to get the device's current battery level with the following:

    Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    Log.i(LOG_FILTER, "Battery level = " + (level*100)/scale);
    // error check values
    if (level == -1 || scale == -1) {
        return -1;
    } else {
        return (level * 100) / scale;
    }

The code seems to work and has never failed me, but I am getting a warning:

Method invocation 'batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)' may produce 'java.lang.NullPointerException'

This may never actually affect my application but as there is an end product depending on it, I am wondering, how might I accommodate this potential issue? Is there a way to reorganize the above to achieve the same result (obtaining the battery's current state of charge)?

advdev1234
  • 30
  • 8

2 Answers2

3

The Javadoc for registerReceiver states:

 * @return The first sticky intent found that matches <var>filter</var>,
 *         or null if there are none.

So there is the potential that this will return you a null event. You already handle the case where the values are invalid ((level == -1 || scale == -1)), so I would recommend that you just check whether the intent is null, and return that value early:

if (batteryIntent == null) {
    return -1;
}
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • 1
    @advdev1234 Just to clarify, if you go this route you'd want to check `batteryIntent == null` before ever trying something like `batteryIntent.getIntExtra(...)` because that's where your NPE would come from. – WOUNDEDStevenJones Aug 11 '15 at 16:03
  • I have added the null intent check prior to querying for the extras and the warning is gone, thanks for your help. @kcoppock Would you say that, since the battery state change intent is fired often and is sticky, that the only reasonably likely scenario that would trigger the null intent is if the battery is somehow missing? – advdev1234 Aug 11 '15 at 16:24
  • @advdev1234 I couldn't say for sure; any time a method states that it can return null in some cases, it's best to handle it though. – Kevin Coppock Aug 11 '15 at 16:25
0

I would throw a try/catch around it because you know it could throw the error, and then you can handle it appropriately if/when it ever does occur.

try {
    //your code here
} catch (NullPointerException e) {
    //handle the error here, maybe return -1?
}
WOUNDEDStevenJones
  • 5,150
  • 6
  • 41
  • 53