我正在尝试实施Android应用内结算。
到目前为止我做了什么:
aidl
文件。util-helper
个文件。signed APK
并将产品添加到Play控制台。Shop.java
文件中添加了一些代码。哪个工作正常,直到我尝试检索商品价格(请参阅下面的代码://THIS IS WHERE THE APP CRASHES
)。以下是我在onCreate()
Shop.java
内使用的代码
onCreate() {
//In App Billing
key = "XXX";
mHelper = new IabHelper(this, key);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
return;
}
if (mHelper == null) return;
Log.d(TAG, "Setup successful. Querying inventory.");
try {
mHelper.queryInventoryAsync(mGotInventoryListener);
} catch (IabHelper.IabAsyncInProgressException e) {
}
}
});
}
然后是mGotInventoryListener
:
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
// Have we been disposed of in the meantime? If so, quit.
if (mHelper == null) return;
if (result.isFailure()) {
// handle error
return;
}
Log.d(TAG, "Query inventory was successful.");
// Do we have the premium upgrade?
Purchase premiumPurchase = inventory.getPurchase(ITEM_SKU);
boolean mIsPremium = (premiumPurchase != null);
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
//THIS IS WHERE THE APP CRASHES
String price = inventory.getSkuDetails(ITEM_SKU).getPrice();
//THIS IS WHERE THE APP CRASHES
updateUI();
}
};
错误消息:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: example.com.app, PID: 4270
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String example.com.app.util.SkuDetails.getPrice()' on a null object reference
at example.com.app.Shop$2.onQueryInventoryFinished(Shop.java:234)
at example.com.app.util.IabHelper$2$1.run(IabHelper.java:711)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
答案 0 :(得分:3)
inventory.getSkuDetails(ITEM_SKU);
返回SkuDetails对象。但是这个对象可以为null
SkuDetails details = inventory.getSkuDetails(ITEM_SKU);
if (details == null) {
return;
};
String price = details.getPrice();