Android应用内购买问题

时间:2016-08-16 14:57:34

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

我在尝试在我已完成的应用上实施应用内购买时遇到了一些严重问题。我有一个类BaseActivity,我的所有其他类都扩展。这是我的工具栏,导航抽屉和IabHelper的设置。

BaseActivity.java:

public abstract class BaseActivity extends AppCompatActivity implements IabBroadcastReceiver.IabBroadcastListener{

public boolean m30paid = false;
public boolean m31paid = false;
public boolean m32paid = false;
public boolean m37paid = false;

static final String ITEM_SKU = "android.test.purchased";

IabHelper mHelper;
IabBroadcastReceiver mBroadcastReceiver;
private final String LOG = BaseActivity.class.getSimpleName();

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

    String base64EncodedPublicKey = "********KEY HERE*********";

    mHelper = new IabHelper(this, base64EncodedPublicKey);
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {
            if (!result.isSuccess()) {
                Log.d(LOG, "Problem setting up in app billing: " + result);
            }
            else Log.d(LOG, "set up correctly!");
            if (mHelper == null) return;
        }
    });
    mBroadcastReceiver = new IabBroadcastReceiver(this);
    IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
    registerReceiver(mBroadcastReceiver, broadcastFilter);
    //IAB fully set up, query inventory
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent data)
{
    if (!mHelper.handleActivityResult(requestCode,
            resultCode, data)) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

@Override
public void onDestroy() {
    super.onDestroy();

    // very important:
    if (mBroadcastReceiver != null) {
        unregisterReceiver(mBroadcastReceiver);
    }

    // very important:
    Log.d(LOG, "Destroying helper.");
    if (mHelper != null) {
        mHelper.disposeWhenFinished();
        mHelper = null;
    }
}

@Override
public void receivedBroadcast() {

}

IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
    public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
        Log.d(LOG, "Query inventory finished.");

        // Have we been disposed of in the meantime? If so, quit.
        if (mHelper == null) return;

        // Is it a failure?
        if (result.isFailure()) {
            complain("Failed to query inventory: " + result);
            return;
        }

        Log.d(LOG, "Query inventory was successful.");

        /*
         * Check for items we own. Notice that for each purchase, we check
         * the developer payload to see if it's correct! See
         * verifyDeveloperPayload().
         */
    }};

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
        Log.d(LOG, "Purchase finished: " + result + ", purchase: " + purchase);

        // if we were disposed of in the meantime, quit.
        if (mHelper == null) return;

        if (result.isFailure()) {
            complain("Error purchasing: " + result);
            return;
        } else if (purchase.getSku().equalsIgnoreCase("workout_30")) {
            m30paid = true;
        }
        Log.d(LOG, "Purchase successful.");
    }
};

void alert(String message) {
    AlertDialog.Builder bld = new AlertDialog.Builder(this);
    bld.setMessage(message);
    bld.setNeutralButton("OK", null);
    Log.d(LOG, "Showing alert dialog: " + message);
    bld.create().show();
}

public void complain(String message) {
    Log.e(LOG, "**** TrivialDrive Error: "+ message);
    alert("Error: " + message);
}

从那里开始,我尝试在另一个类的按钮上设置launchPurchaseFlow。

Purchases.java:

public class purchases extends BaseActivity {

IabHelper mHelper;
static final String ITEM_SKU = "android.test.purchased";
IabBroadcastReceiver mBroadcastReceiver;
Context mContext;
Activity mActivity = this;
static final int RC_REQUEST = 10001;
private Button btn30;
static final String SKU_W30 = "workout_30";
String payload = "";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.purchases);
    mToolBar = activateToolbar();
    setUpNavigationDrawer();
    getSupportActionBar().setTitle("Purchases");

    btn30 = (Button) findViewById(R.id.btn30);
    Button btn31 = (Button) findViewById(R.id.btn31);
    Button btn32 = (Button) findViewById(R.id.btn32);
    Button btn37 = (Button) findViewById(R.id.btn37);

    btn30.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                mHelper.launchPurchaseFlow(purchases.this, SKU_W30, RC_REQUEST, mPurchaseFinishedListener, payload);
            } catch (IabHelper.IabAsyncInProgressException e) {
                complain("Error");
            }
        }
    });
}
}

单击按钮时出现的错误是:

FATAL EXCEPTION: main
                                                                          Process: com.bestworkouts.sheikoworkout, PID: 4118
                                                                          java.lang.NullPointerException: Attempt to invoke virtual method 'void com.bestworkouts.sheikoworkout.util.IabHelper.launchPurchaseFlow(android.app.Activity, java.lang.String, int, com.bestworkouts.sheikoworkout.util.IabHelper$OnIabPurchaseFinishedListener, java.lang.String)' on a null object reference
                                                                              at com.bestworkouts.sheikoworkout.purchases$1.onClick(purchases.java:41)
                                                                              at android.view.View.performClick(View.java:5697)
                                                                              at android.widget.TextView.performClick(TextView.java:10814)
                                                                              at android.view.View$PerformClick.run(View.java:22526)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:158)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

基本上我想要它做的是在onIabPurchaseFinished中,将布尔值更改为true。我在expLV上有一个if语句,所以如果布尔值为false,则表示你需要购买它,如果是真的,它会提供访问权限。到目前为止,这部分工作正常,但我似乎无法通过此错误来查看它是否正确更改了布尔值并解锁了数据。

我不确定我错过了什么,而且我已经弄乱了它并且在2天内处理了多个错误..任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:1)

子类变量mHelper未初始化。尝试从IabHelper mHelper;类中删除purchaseBaseActivity扩展mHelper,其中mHelper已初始化。

在子类中声明mHelper将隐藏超类var events = [ ["cell1", "cell2", "cell3", "cell4"], ["cell1", "cell2", "cell3", "cell4"] ] for (var i = 0; i < events.length; i += 1) { for (var y = 0; y < events[i].length; y += 2) { var row = document.createElement('tr'); var cell = document.createElement('td'); var text = document.createTextNode(events[i][y]); cell.className = 'left_table_head'; cell.appendChild(text); row.appendChild(cell); var text = document.createTextNode(events[i][y + 1]); var cell = document.createElement('td'); if (y == 0) { cell.className = 'right_table_head'; } if (events[i][y + 1] === '') { cell.className += ' empty'; } cell.appendChild(text); row.appendChild(cell); document.getElementById('mobile-responsive').appendChild(row); } }变量。