I made a class for handling important data changes such as App Purchase Status and other stuff .
For this goal I have created a class which does the setting and read
you are setting the default value to true, so either your sharedpreference does not contains an entry for key_purchased or setAppInPurchasedMode
is never called or is called wit status successful
. On the minor side, your
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
can be implemented like:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase, false);
}
about setAppInPurchasedMode
, if I were in you I would change the way you compare status
, this way:
public void setAppInPurchasedMode(String status){
if ("successful".equals(status)){
settings.edit().putBoolean(keyPurchase, true).commit();
} else if ("failed".equals(status)){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
the difference is that if status
is null, the way you implemented will crash your application with NPE. With my implementation you'll get false, because "successful" instanceof
null is always false, and instanceof
is the first check for equals
Found It, the problem is that I was thinking
settings.getBoolean(keyPurchase,false)
returns the value of keyPurchased variable but the fact is it only returns the variable itself not its value so I fixed the problem by changing the method of my class to this:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase,false);
}
Actually there is a problem in your code!! thats why its always showing purchased!!
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
in this lines if the keyPurchased tag if not used , u are passing true value by default so when u call
if (appCore.appIsPurchased()){
it always return a true value.. The solution is that make sure that the preference values are set before u call them.. hope this helps
For those still having a problem, remember to apply the changes to your preferences.
private SharedPreferences sharedPreferences ;
private SharedPreferences.Editor sharedPreferencesEditor;
sharedPreferencesEditor.putBoolean("myVariable", false);
sharedPreferencesEditor.apply();