admiral
admiral

Reputation: 163

Problems with getting context

I made an application that works with play services. I tested my app on HTC 310, nexus, lenovo p780 and some other devices. It doesn't crash at all. I have installed Crashlytics and recieve some weird crash report:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
       at com.preferences.iaps.IabHelper.queryPurchases(IabHelper.java:829)
       at com.preferences.iaps.IabHelper.queryInventory(IabHelper.java:557)
       at com.preferences.iaps.IabHelper.queryInventory(IabHelper.java:521)
       at com.preferences.iaps.IabHelper$2.run(IabHelper.java:614)
       at java.lang.Thread.run(Thread.java:818)

I get this error from samsungs like s4, s5. Is there a problem with these devices or there is a problem in the app?

Here is an example when i call and pass context to Iabhelper:

   @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            mActivity = activity;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setRetainInstance(true);

            mHelper = new IabHelper(mActivity, base64EncodedPublicKey);
            mHelper.enableDebugLogging(true);
            mHelper.startSetup(this);
        }

Here is what is causing the threw null pointer exception: (line 829):

 logDebug("Package name: " + mContext.getPackageName());

This is where I get the context (same class where error)

public IabHelper(Context ctx, String base64PublicKey) {
        mContext = ctx.getApplicationContext();
        mSignatureBase64 = base64PublicKey;
        logDebug("IAB helper created.");
    }

Upvotes: 4

Views: 579

Answers (2)

kc ochibili
kc ochibili

Reputation: 3131

try getActivity().getApplicationContext();

Upvotes: 0

Quintin B
Quintin B

Reputation: 5881

Do you have the same issue if you use the following:

mHelper = new IabHelper(getActivity(), base64EncodedPublicKey);

EDIT I have noticed the error is in your class:

com.preferences.iaps.IabHelper.queryPurchases(IabHelper.java:829)

Are you sure you have persisted the context variable in the constructor if the IabHelper, and are using the same variable in the queryPurchases?

EDIT2

logDebug("Package name: " + mContext.getPackageName());

mContext is null in the class - you need to make sure you set it in the constructor of IabHelper

Upvotes: 2

Related Questions