Pedro Lobito
Pedro Lobito

Reputation: 99061

Android SharedPreferences Boolean not working

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.

Upvotes: 1

Views: 2300

Answers (3)

Patrik Onderka
Patrik Onderka

Reputation: 106

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.

Upvotes: 1

Nargis
Nargis

Reputation: 4787

SharedPrefernces are saved in key:value pairs ,you are putting value in "PREMIUM" and retreiving as "PRIVATE"

Upvotes: 2

Marko Niciforovic
Marko Niciforovic

Reputation: 3601

mIsPremium = pref.getBoolean("PREMIUM", false); 

NOT ("PRIVATE",false)

You are using different keys, they need to match.

Upvotes: 8

Related Questions