Thursday, November 3, 2011

NullPointerException in IntentService

0x000000

NullPointerException.  My all time favorite Java exception.  Probably the single most common exception in Java.  Richly ironic, isn't it?  For a language that doesn't have "pointers?"

Anyway, my latest encounter with NPE was one thrown from the Android framework in the constructor of my IntentService-derived class.

Try it:

public class MyService extends IntentService {



    public MyService() {

        super("MySericeName");

        String s = this.getPackageName();




NullPointerException at
android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)

Here's the inheritance hierarchy:

The no-args constructor of Service, which extends ContextWrapper, calls super(null).  So wrapper is wrapping null.

ContextWrapper doesn't do much of anything but delegate calls to the real context that it's given.  So if you try to make any calls on the Context during construction, you will get an NPE.

Your IntentService derived class, although it gets instantiated when the app starts, will not get a Context until it gets "attached."

That happens before your onHandleIntent method gets invoked.  So anything that needs a Context will have to wait until onHandleIntent gets called.


No comments:

Post a Comment