Iab Helper软件包名称

时间:2018-08-08 06:27:09

标签: android nullpointerexception in-app-billing android-inapp-purchase

我正在尝试添加应用帐单并出错

Chech试用活动是我的启动活动,我正在尝试检查是否购买了此应用的用户, 这是我的ChechActivity:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.trial);
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    if (settings.getBoolean("my_first", true)) {
        settings.edit().putLong("time",System.currentTimeMillis() / 1000).commit();
        settings.edit().putBoolean("my_first", false).commit();
    }
    Log.e("currenttime",String.valueOf(System.currentTimeMillis() / 1000));
    Log.e("savedtime",String.valueOf(settings.getLong("time",System.currentTimeMillis() / 1000)));

    if((System.currentTimeMillis() / 1000)-settings.getLong("time",System.currentTimeMillis() / 1000)>=43200){ /////////// trial time  = 43200 seconds equal to 12 hours
        settings.edit().putBoolean("trial",false).commit();
    }
    if (settings.getBoolean("trial", true)||settings.getBoolean("auth",false)) {
        //// settings.getBoolean("trial", true) -----> trial time not expired  ////   settings.getBoolean("auth",false) ---> user email has regidtred on server
        Intent intent = new Intent(ChechTrial.this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.ss);
        if (fragment == null) {
            fragment = new GPlusFragment();
            fm.beginTransaction()
                    .add(R.id.ss, fragment)
                    .commit();
        }
    }
    checkAccount();
}
private void checkAccount() {
    iabHelper = new IabHelper(ChechTrial.this, KEY);
    iabHelper.startSetup(ChechTrial.this);
}

/* private void checkUserHasSubscription() {

     subSharedPreference = ((MainActivity) getActivity()).getSharedPreferences(SHP_NAME, Context.MODE_PRIVATE);
     isSubscription = subSharedPreference.getBoolean("sub", false);
     if (!(isSubscription)) {
         // show progress bar until data receive from google play
         iabHelper = new IabHelper(getContext(), KEY);
         iabHelper.startSetup(this);
     }
 }

@Override
public void onIabSetupFinished(IabResult result) {
    if (result.isSuccess()) {
        List<String> products = new ArrayList<>();
        products.add(PREMIUM);

        iabHelper.queryInventoryAsync(true, products, ChechTrial.this);
        //    iabHelper.queryInventoryAsync(this);


    }
}

@Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
    if (result.isSuccess()) {
        Purchase purchase = inv.getPurchase(PREMIUM);
        // Purchase purchase1 = inv.getPurchase("sslink");
        /*if (purchase1 != null) {
            SharedPreferences.Editor editor = subSharedPreference.edit();
            editor.putBoolean("sub", true);
            editor.apply();
        } else {
            SharedPreferences.Editor editor = subSharedPreference.edit();
            editor.putBoolean("sub", false);
            editor.apply();
        }*/
        if (purchase != null) {
            subSharedPreference =getSharedPreferences(SHP_NAME,MODE_PRIVATE);
            subSharedPreference.edit().putBoolean("Nconsume_isPurchase",true).apply();
        } else {
            subSharedPreference.edit().putBoolean("Nconsume_isPurchase",false).apply();
        }
    }
}


public void purchasePremiumAccount() {
    if (iabHelper != null) {
        iabHelper.flagEndAsync();
    }
    iabHelper.launchPurchaseFlow(this, PREMIUM, 1006, new IabHelper.OnIabPurchaseFinishedListener() {
        @Override
        public void onIabPurchaseFinished(IabResult result, Purchase info) {
            if (result.isSuccess()) {
                if (info != null) {
                    subSharedPreference =getSharedPreferences(SHP_NAME,MODE_PRIVATE);
                    subSharedPreference.edit().putBoolean("Nconsume_isPurchase",true).apply();
                }
            }
        }
    });

}

@Override
protected void onDestroy() {
    if (iabHelper != null) {

        iabHelper.dispose();

        iabHelper = null;
    }
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1006) {
        iabHelper.handleActivityResult(requestCode, resultCode, data);
    }else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

}

调用onCreate时调用checkAccount并发生错误

这是我的堆栈跟踪:

08-08 10:36:00.214 29037-29166/com.secondsstore.sslink E/Pushe: Exception caught 
                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                at com.secondsstore.sslink.util.IabHelper.querySkuDetails(IabHelper.java:916)
                                                                at com.secondsstore.sslink.util.IabHelper.queryInventory(IabHelper.java:550)
                                                                at com.secondsstore.sslink.util.IabHelper.queryInventory(IabHelper.java:522)
                                                                at com.secondsstore.sslink.util.IabHelper$2.run(IabHelper.java:617)
                                                                at java.lang.Thread.run(Thread.java:833)

因为IabHelper类太久了,所以我放置了一些可以从堆栈跟踪中了解的方法:

 int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
                            throws RemoteException, JSONException {
    logDebug("Querying SKU details.");
    ArrayList<String> skuList = new ArrayList<String>();
    skuList.addAll(inv.getAllOwnedSkus(itemType));
    if (moreSkus != null) {
        for (String sku : moreSkus) {
            if (!skuList.contains(sku)) {
                skuList.add(sku);
            }
        }
    }

    if (skuList.size() == 0) {
        logDebug("queryPrices: nothing to do because there are no SKUs.");
        return BILLING_RESPONSE_RESULT_OK;
    }

    Bundle querySkus = new Bundle();
    querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList);
    Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(),
            itemType, querySkus);

    if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
        int response = getResponseCodeFromBundle(skuDetails);
        if (response != BILLING_RESPONSE_RESULT_OK) {
            logDebug("getSkuDetails() failed: " + getResponseDesc(response));
            return response;
        }
        else {
            logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
            return IABHELPER_BAD_RESPONSE;
        }
    }

    ArrayList<String> responseList = skuDetails.getStringArrayList(
            RESPONSE_GET_SKU_DETAILS_LIST);

    for (String thisResponse : responseList) {
        SkuDetails d = new SkuDetails(itemType, thisResponse);
        logDebug("Got sku details: " + d);
        inv.addSkuDetails(d);
    }
    return BILLING_RESPONSE_RESULT_OK;
}



public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus,
                                    List<String> moreSubsSkus) throws IabException {
    checkNotDisposed();
    checkSetupDone("queryInventory");
    try {
        Inventory inv = new Inventory();
        int r = queryPurchases(inv, ITEM_TYPE_INAPP);
        if (r != BILLING_RESPONSE_RESULT_OK) {
            throw new IabException(r, "Error refreshing inventory (querying owned items).");
        }

        if (querySkuDetails) {
            r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus);
            if (r != BILLING_RESPONSE_RESULT_OK) {
                throw new IabException(r, "Error refreshing inventory (querying prices of items).");
            }
        }

        // if subscriptions are supported, then also query for subscriptions
        if (mSubscriptionsSupported) {
            r = queryPurchases(inv, ITEM_TYPE_SUBS);
            if (r != BILLING_RESPONSE_RESULT_OK) {
                throw new IabException(r, "Error refreshing inventory (querying owned subscriptions).");
            }

            if (querySkuDetails) {
                r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus);
                if (r != BILLING_RESPONSE_RESULT_OK) {
                    throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions).");
                }
            }
        }

        return inv;
    }
    catch (RemoteException e) {
        throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e);
    }
    catch (JSONException e) {
        throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e);
    }
}

 public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException {
    return queryInventory(querySkuDetails, moreSkus, null);
}
 public void queryInventoryAsync(final boolean querySkuDetails,
                           final List<String> moreSkus,
                           final QueryInventoryFinishedListener listener) {
    final Handler handler = new Handler();
    checkNotDisposed();
    checkSetupDone("queryInventory");
    flagStartAsync("refresh inventory");
    (new Thread(new Runnable() {
        public void run() {
            IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
            Inventory inv = null;
            try {
                inv = queryInventory(querySkuDetails, moreSkus);
            }
            catch (IabException ex) {
                result = ex.getResult();
            }

            flagEndAsync();

            final IabResult result_f = result;
            final Inventory inv_f = inv;
            if (!mDisposed && listener != null) {
                handler.post(new Runnable() {
                    public void run() {
                        listener.onQueryInventoryFinished(result_f, inv_f);
                    }
                });
            }
        }
    })).start();
}

1 个答案:

答案 0 :(得分:0)

启动IabHelper时,活动上下文可能尚未准备好。尝试使用应用程序上下文:

private void checkAccount() {
    iabHelper = new IabHelper(getApplicationContext(), KEY);
    ...
}