Question

I have an IntentService that implements LocationListener. It runs while my application is running, and is destroyed when my application is closed. In its onHandleIntent method I get a LocationManager and register the service form location updates. In its onDestroy method, I call:

locationManager.removeUpdates(this);

However, this sometimes causes a NullPointerException:

08-23 20:45:09.826: ERROR/AndroidRuntime(6541): FATAL EXCEPTION: main
08-23 20:45:09.826: ERROR/AndroidRuntime(6541): java.lang.RuntimeException: Unable to stop service uk.ac.ic.doc.vmw10.wherewolf.helpers.Locater@44f53fa8: java.lang.NullPointerException
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.handleStopService(ActivityThread.java:3090)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.access$3700(ActivityThread.java:125)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2099)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.os.Looper.loop(Looper.java:123)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at java.lang.reflect.Method.invokeNative(Native Method)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at java.lang.reflect.Method.invoke(Method.java:521)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at dalvik.system.NativeStart.main(Native Method)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541): Caused by: java.lang.NullPointerException
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at uk.ac.ic.doc.vmw10.wherewolf.helpers.Locater.onDestroy(Locater.java:137)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.handleStopService(ActivityThread.java:3076)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     ... 10 more

If I remove that line, the NullPointerException goes away, but the LocationListener doesn't stop when I close my application. Any ideas how I can fix this?

Was it helpful?

Solution

How about wrapping it in a null check?

if (locationManager != null)
    locationManager.removeUpdates(this);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top