我试图设置一个简单的应用内购买,但由于某种原因,当我尝试查询可用的项目时,我总是得到一个空指针。我尝试使用Handler
查看这是否是等待的问题,但这也没有用,它只是阻止代码运行。
public class AdOnsActivity extends AppCompatActivity {
private IInAppBillingService mService;
private ServiceConnection mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ad_ons);
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
ArrayList<String> skuList = new ArrayList<String>();
skuList.add(PRODUCT_ID_MORE_REPTILES);
final Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mService != null) {
//Query items here
} else {
handler.postDelayed(this, 10);
}
}
}, 10);
buttonBuy = (Button) findViewById(R.id.buttonBuy);
buttonBuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), PRODUCT_ID_MORE_REPTILES, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), 0, 0, 0);
} catch (RemoteException|IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001) {
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
if (resultCode == RESULT_OK) {
try {
JSONObject json = new JSONObject(purchaseData);
String sku = json.getString("productId");
Toast.makeText(this, "Congratulations on your purchase!", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mService != null) {
unbindService(mServiceConn);
}
}
答案 0 :(得分:0)
用于显示导致NPE的代码的堆栈跟踪将非常方便。但我会假设您的意思是mService
来电onCreate
始终为空。
你本质上是在做糟糕的程序设计。获取应用内商品是一种网络电话。并且您不应该使用onCreate
方法进行Aysnchronous网络通话。
相反,填充一个空间供IAP使用。然后当你获得onServiceConnected()时,触发listProducts()
调用。然后当queryProducts()
获得结果时填充ListView或您创建的任何内容。否则,对于始终处于离线状态的用户来说,您会遇到糟糕的体验。