4

I create a IabHelper object in a Service, but sometimes it throws a NullPointerException, that I found out is due to context.getApplicationContext() that sometimes return null int the constructor of IabHelper.

In other words, context.getApplicationContext() sometimes returns null, but I cannot understand why.

The IabHelper object is the one described here, slightly modified.

Here's what I do: in the onCreate() method of the Service, construct an IabHelper object:

public class MyService extends Service {

    IabHelper helper;
    ...

    public void onCreate() {
      super.onCreate();
      ...
      helper = new IabHelper(this);
      ...
    }
}

Here this should not be null. The IabHelper object is something like this:

public class IabHelper {
  Context context;

  public IabHelper(Context ctx) {
    context = ctx.getApplicationContext();
    ...
  }
  ...
}

Then, as explained above, when I call context.getPackageName() or any other method, a NullPointerException is thorwn. This happened only 7 times in a month over about 50 users (in fact I was not able to reproduce it).

The only similar problem I found was this one, but I don't run the Service in another process, so it is not my case.

Any ideas? Thanks in advance.

Community
  • 1
  • 1
vector
  • 99
  • 8
  • Have you tried just calling the getApplicationContext without the context ? I run a service that uses getApplicationContext without a parent context and I never faced this kind of errors. – Carlos Jan 12 '16 at 16:59
  • I cannot do this because IabHelper is an external class that doesn't extend anything, and `getApplicationContext()` is a method of `Context` (`Service` extends `Context`, so you can call the method from it) – vector Jan 12 '16 at 17:15
  • Doesnt your service extends Service ? Because getApplicationContext is a method of Service -> http://developer.android.com/intl/pt-br/reference/android/app/Service.html – Carlos Jan 12 '16 at 17:19
  • Yes, but `getApplicationContext()` is not called from the service, but in the constructor of `IabHelper`, that does not extend `Context`. I pass the service as an argument of the constructor, from which I try to call `getApplicationContext()`, which returns `null` sometimes. – vector Jan 12 '16 at 17:47

0 Answers0