Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException in IabHelper.queryPurchases

Today I discovered an application crash report for my Android app involving the following stack trace:

java.lang.NullPointerException: Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getPurchases(int, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.myapp.utils.IabHelper.queryPurchases(IabHelper.java:878)
at com.myapp.utils.IabHelper.queryInventory(IabHelper.java:572)
at com.myapp.utils.IabHelper.queryInventory(IabHelper.java:545)
at com.myapp.utils.IabHelper$2.run(IabHelper.java:645)
at java.lang.Thread.run(Thread.java:818)

(line numbers are changed from the original -or what looks like to be the original, because of custom reformatting)

Normally, one would modify his own code to check for unassigned class members. The problem is that this code is copied&pasted right from Android SDK, because IabHelper is a class that Android SDK provides as a good starting point for implementing In-app Billing v3

The guilty line is the second

logDebug("Calling getPurchases with continuation token: " + continueToken);
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);

It seems that the service is not connected at the time the method is invoked. This error occurred on a Nexus 5 device (as per Developer Console)

  • Is this a known problem with Android 5?
  • Is there an up-to-date version of the IAB Helper?
  • What can I do rather than manually editing the code to handle NPE someway?
like image 267
usr-local-ΕΨΗΕΛΩΝ Avatar asked Dec 15 '14 09:12

usr-local-ΕΨΗΕΛΩΝ


1 Answers

I modified this code ...

    do {
        logDebug("Calling getPurchases with continuation token: " + continueToken);
        Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);
        // ...
    }

To be this ...

    do {
        logDebug("Calling getPurchases with continuation token: " + continueToken);
        if (mService == null || mContext == null) {
            logError("Our service and/or our context are null.  Exiting.");
            return IABHELPER_UNKNOWN_ERROR;
        }
        Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);
        // ...
    }

This is almost certainly because the process is being run asynchronously and the activity/app has (or is being) closed when the result returns.

like image 151
Bill Mote Avatar answered Oct 29 '22 00:10

Bill Mote