Android: The Mysterious NullPointerException

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.

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.

This Post Has 2 Comments

  1. Thank you!!!

  2. 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 :)

Leave a Reply

Close Menu