Search code examples
androidonresumeonpause

My onResume() throws a NullPointerException


I am taking accelerometer readings to catch users shaking the phone. When a user shakes the phone, I want to design it to do something. It works fine, but I put in an onPause() method because I don't need the accelerometer detecting any shaking motions when the user isn't within the app, as that would have undesired results. So in the onPause() I unregister the accelerometer from the SensorManager.

It was my hope that in onResume() I could re-register the SensorManager, and go about my business. Obviously it isn't quite working that way. I've read the documentation and, honestly, I haven't been able to figure out what is going on.

Code:

I declare global variable sensorMgr:

private SensorManager sensorMgr;

Then I register it to the accelerometer:

sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);

    // Detect if device has accelerometer
    boolean accelSupported = sensorMgr.registerListener(this,
            SensorManager.SENSOR_ACCELEROMETER,
            SensorManager.SENSOR_DELAY_GAME);

    if (!accelSupported) {
        // No accelerometer on this device
        sensorMgr.unregisterListener(this,
                SensorManager.SENSOR_ACCELEROMETER);
    }
    sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER,
            SensorManager.SENSOR_DELAY_GAME);

onPause():

protected void onPause() {
    if (sensorMgr != null) {
        sensorMgr.unregisterListener(this,
                SensorManager.SENSOR_ACCELEROMETER);
        sensorMgr = null;
    }
    super.onPause();
}

onResume():

protected void onResume() {
    sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER,
        SensorManager.SENSOR_DELAY_GAME);
    super.onResume();
}

The error:

05-24 14:35:54.058: E/AndroidRuntime(16783): java.lang.RuntimeException: Unable to resume activity : java.lang.NullPointerException

I really appreciate any help you guys can give, and thanks in advance!


Solution

  • sensorMgr is null when you reach onResume(), since you forcibly set it to null in your onPause() method. Reinitialize sensorMgr (getSystemService(...)) before calling registerListener().