Search code examples
androidandroid-billing

Android: How to restore previous purchased using Android billing 4.0.0


I'm trying to create a "Restore" button (just like in iOS) so the user can restore his previous purchases. I'm using the code below, but List<Purchase> list comes back empty. I made a real purchase with a credit card, then I delete the app and reinstall from the Google Play Store, but I can't get it the "Restore" button to work. Here is the code I'm using for my "Restore" button:

private void restorePreviousPuchases () {

    billingClient.queryPurchasesAsync(BillingClient.SkuType.INAPP, new PurchasesResponseListener() {
        @Override
        public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) {

            if (list != null) {

                for (Purchase purchase : list) {
                    ArrayList<String> skus = purchase.getSkus();

                    if (skus != null) {
                        for (String sku : skus) {
                            setPurchasedItem(sku);

                        }
                    }

                }

            } else {
                Log.d("DEBUGGING...", "onCreate: NULL purchaseList" );
            }
        }
    });
    
}

Solution

  • I just had the same issue. After investigating a bit, it seems that this is a known bug.

    However, if you initiate your billing client first and then call queryPurchase it works. Just don't put this inside the oncreate (didn't work for me).

    BillingClient billingClient;

        public void setupBillingClient(){
    
         billingClient = BillingClient.newBuilder(mContext)
                .setListener(purchasesUpdatedListener)
                .enablePendingPurchases()
                .build();
    
        startConnection();
    }
    
    public void queryPurchases(Boolean consume){
    
            if (billingClient!=null) {
                billingClient.queryPurchasesAsync(BillingClient.SkuType.INAPP, new PurchasesResponseListener() {
    
                    @Override
                    public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) {
    
                            for (int i = 0; i < list.size(); i++){
                                    consumePurchase(list.get(i));
                                }
                        
                    }
                });
            }
        }