问题
I'm trying to get a boolean value from SharedPreferences that is true but I'm getting a false value every time. The SharedPreferences file named "MyPref"contains the following code:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="PREMIUM" value="true" />
</map>
I'm adding values to SharedPreferences in MyActivity.class using the following code:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 1); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("PREMIUM", true); // Storing boolean - true/false
editor.commit(); // commit changes
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
And retrieving it on multiple classes by using:
boolean mIsPremium = false;
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 1); // 0 - for private mode
mIsPremium = pref.getBoolean("PRIVATE", false); // getting boolean
Log.d("IS PREMIUM", String.valueOf(mIsPremium));
if(mIsPremium) {
// PREMIUM USER - NO ADS
} else {
// NOT PREMIUM USER - SHOW ADS
}
I'm always getting the value of Premium as false, what could be the reason for this to happen and how to solve it ? I'm using android 4.2.2. Thank you all.
回答1:
mIsPremium = pref.getBoolean("PREMIUM", false);
NOT ("PRIVATE",false)
You are using different keys, they need to match.
回答2:
SharedPrefernces are saved in key:value pairs ,you are putting value in "PREMIUM" and retreiving as "PRIVATE"
回答3:
You changed keys "PREMIUM" and "PRIVATE". Using of hardcoded strings is a generally bad programming practice. I would recommend using final static variables for these.
来源:https://stackoverflow.com/questions/17487101/android-sharedpreferences-boolean-not-working