The Problem
One day it was just there. A mischievous NullPointerException causing, eh, mischief. It was fairly easy to provoke with my application but for some reason my code was not part of the stacktrace.
12-07 14:42:52.722 E/AndroidRuntime(18421): FATAL EXCEPTION: main 12-07 14:42:52.722 E/AndroidRuntime(18421): java.lang.NullPointerException 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1064) 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1081) 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.os.Handler.handleCallback(Handler.java:587) 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.os.Handler.dispatchMessage(Handler.java:92) 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.os.Looper.loop(Looper.java:130) 12-07 14:42:52.722 E/AndroidRuntime(18421): at android.app.ActivityThread.main(ActivityThread.java:3701) 12-07 14:42:52.722 E/AndroidRuntime(18421): at java.lang.reflect.Method.invokeNative(Native Method) 12-07 14:42:52.722 E/AndroidRuntime(18421): at java.lang.reflect.Method.invoke(Method.java:507) 12-07 14:42:52.722 E/AndroidRuntime(18421): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 12-07 14:42:52.722 E/AndroidRuntime(18421): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 12-07 14:42:52.722 E/AndroidRuntime(18421): at dalvik.system.NativeStart.main(Native Method)
I fretted. I winced. I even felt a slight irritation coming on.
The Solution
In the end I found out the reason behind the mysterious NullPointerException. My application is binding to a Service and it turns out that the ContextWrapper.bindService()-method can’t take a null as its ServiceConnection parameter.
ContextWrapper.bindService():
public boolean bindService (Intent service, ServiceConnection conn, int flags)
Connect to an application service, creating it if needed.
Instead of throwing a helpful IllegalArgumentException it forwards the erroneous null-parameter into the innards of The Android Service Beast. That part is then unable to use it and throws a NullPointerException instead together with its own stacktrace which your code is not a part of.
The Summary
In short, make sure you don’t pass bindService() a null as the ServiceConnection parameter or you will get an unknown NullPointerException which is hard to track down.
Thank you!!!
For those who do not know already, git bisect is a VERY powerful tool for tracking down this kind of buggs and others to, provided that you do git commit often as a good gitter should :)