Reputation: 721
I am trying to use
BillingDataSource.java
Security.java
from TrivialDriveSample I managed to get the purchase for a Premium SKU (one time purchase) but where can I check if this product is bought when my App start in order to unlock features each time the App starts I need to call from my MainActivity a method to see if it is ok
if I ask
@Override
public void onResume() {
super.onResume();
LiveData<Boolean> IsPremiumPurchased = ((MainActivity)getActivity()).billingDataSource.isPurchased(SKU_PREMIUM);
mIsPremium = IsPremiumPurchased.getValue();
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
((MainActivity)getActivity()).updateUi();
}
I got Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference at com.xxxxxxxxxxx.MainActivity$MainFragment.onResume(MainActivity.java:1302)
because IsPremiumPurchased is not valid
Upvotes: 2
Views: 449
Reputation: 721
After trying, right answer is
billingDataSource = new BillingDataSource( this.getApplication(),
INAPP_SKUS, SUBSCRIPTION_SKUS, AUTO_CONSUME_SKUS);
LiveData<Boolean> IsPremiumPurchased = billingDataSource.isPurchased(SKU_PREMIUM);
final Observer<Boolean> premiumPurchasedObserver = new Observer<Boolean>() {
@Override
public void onChanged(@Nullable final Boolean isPurchased) {
mIsPremium = isPurchased;
updateUi();
Log.d(TAG, "premiumPurchasedObserver changed");
}
};
IsPremiumPurchased.observe(this, premiumPurchasedObserver);```
Upvotes: 0
Reputation: 854
As I see a sample use live-data and data-binding.
From your code:
((MainActivity)getActivity()).billingDataSource.isPurchased(SKU_PREMIUM)
You get live-data object IsPremiumPurchased
but live-data provides observe pattern to receive new values. It's means that usually you can't get value sync by calling IsPremiumPurchased.getValue()
because operation of getting value by key SKU_PREMIUM
is async and will be written to IsPremiumPurchased
after some time. That's why call to IsPremiumPurchased.getValue()
returns null
in your snippet(As you can see it valid behaviour). Right way to use IsPremiumPurchased
- is subscribe to updates of IsPremiumPurchased
like in this sample.
For example you can put code like this to onCreate
method:
final Observer<Boolean> premiumPurchasedObserver = new Observer<Boolean>() {
@Override
public void onChanged(@Nullable final Boolean isPurchased) {
mIsPremium = isPurchased;
((MainActivity)getActivity()).updateUi();
}
};
IsPremiumPurchased.observe(this, premiumPurchasedObserver);
mIsPremium = IsPremiumPurchased.getValue();
if(mIsPremium == null) {
mIsPremium = false
}
((MainActivity)getActivity()).updateUi();
I Add check for current value after IsPremiumPurchased.observe
call to get consistent ui if premiumPurchasedObserver.onChanged
will be called with long delay.
Upvotes: 1