This is actually two questions:
- The first relates to my program
- The second is a more general question regarding debugging.
In my code, I have two button listeners. When the first is clicked, the onClickListener creates the locationlistener as well as the LocationManager which requests updates from the locationlistener. (See code below.)
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationlistener);
On the click of the second button, I try to unregister the listener as follows:
locationManager.removeUpdates(locationlistener);
However, I end up with a force close and the following info in the debugger:
ERROR/AndroidRuntime(310): FATAL EXCEPTION: main
ERROR/AndroidRuntime(310): java.lang.NullPointerException
ERROR/AndroidRuntime(310): at com.ryan.gcal.GRunCal$2.onClick(GRunCal.java:94)
ERROR/AndroidRuntime(310): at android.view.View.performClick(View.java:2408)
ERROR/AndroidRuntime(310): at android.view.View$PerformClick.run(View.java:8816)
ERROR/AndroidRuntime(310): at android.os.Handler.handleCallback(Handler.java:587)
ERROR/AndroidRuntime(310): at android.os.Handler.dispatchMessage(Handler.java:92)
ERROR/AndroidRuntime(310): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(310): at android.app.ActivityThread.main(ActivityThread.java:4627)
ERROR/AndroidRuntime(310): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(310): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(310): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
ERROR/AndroidRuntime(310): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
ERROR/AndroidRuntime(310): at dalvik.system.NativeStart.main(Native Method)
Line 94 of my code, where the error originates, is where I tried to remove the location listener. So, I assume I am not removing the location listener properly, but I am not sure what is wrong. My LocationManager is declared at the start of my code:
Locationmanager locationManager;
My first question is, what am I doing wrong in removing the listener? And secondly, can anyone provide some tips/advice on learning to interpret debug errors meaningfully?
Thanks.
You need to either:
A) define the locationManager instance as a class variable, or retrieve it again in your onclick.
You need to make sure that in onClick1() instead of
you put
Specifying LocationManager locationManager makes the scope of your declaration enclosed to the method its assign in, rather than in the scope of the class. This means in your 2nd click locationManager is infact null.