Search code examples
androidservicenullpointerexceptionbilling

In Dungeons-based billing service, bindService returns NullPointerException


I am implementing a billing service based on the Dungeons sample (which is the way Google recommend you go about it). It's slightly complicated by the following facts:

  1. The main service class lives in a library project (because I want to reskin the code many times). As this stackoverflow answer suggests a service in a library project may cause problems, I have made the service abstract and inherited it in the sub-projects; this also lets me use different public keys for each reskin (which is desirable).
  2. There are plenty of UI elements that need to know if billing is supported as soon as possible.

Consequently I am calling a function to check if billing is supported from the onCreate() method of the first activity run (actually any activity, but a preference will then be written so this should only happen once).

In the Dungeons sample, the code to check if billing is supported tries to bind to the billing service thus (from the Service class):

boolean bindResult = bindService(
    new Intent(Consts.MARKET_BILLING_SERVICE_ACTION),
    this,  // ServiceConnection.
    Context.BIND_AUTO_CREATE);

this call is throwing a NullPointerException. I've checked pretty carefully and none of these things are null; it's occurring within the function, apparently at line 370 of ContextWrapper.java.

Because of this other stackoverflow answer I wondered if checking billing from onCreate() might be premature but the Dungeons example project, again, calls it from here, so I don't think it's this.

I am using a much later version of Android (3.1) so that might have an effect, but I'd love to know the possible causes of this. One other thing: Eclipse is telling me customIntent is null, but it's not fully clear what that refers to and I've not been able to find much about it.


Solution

  • The answer turns out to be very, very simple: I missed this step in Activity#onCreate:

    mBillingService = new BillingService()
    
    //THIS STEP IS THE CRITICAL STEP
    mBillingService.setContext(this);
    //IF ONLY I HAD KNOWN
    
    mBillingService.checkBillingSupported();
    

    This calls attachBaseContext(context);

    It works now :)