Ahmed S. Durrani
Ahmed S. Durrani

Reputation: 1585

SharedPreferences not Reading

I am getting weird problem with my app. I have set-up one SharedPreference, like this

SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        flag = prefs.getBoolean("handle_calls", false);
        if (flag) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
            editor.putBoolean("checkFlag", true);
            editor.commit();
        }

it was working fine some days before, but now this code is working fine but when I try to read these preferences in my SmsReceiver Class SharedPreferences doesnt read these values and default values are read (false)...Sometimes it work and most of the time it doesnt work at all! Here is how I am reading the SharedPreferences

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SmsManager sms = SmsManager.getDefault();

    //flag = prefs.getBoolean("handle_calls", false);
    checkFlag = prefs.getBoolean("checkFlag", false);
    checkDecisionFlag = prefs.getBoolean("checkDecisionFlag", false);

This checkDecisionFlag is working fine but checkFlag is taking default values.

Really pissed! Please Help!

Upvotes: 2

Views: 245

Answers (3)

Ahmed S. Durrani
Ahmed S. Durrani

Reputation: 1585

Solved it! This code was fine, instead the problem was with the life-cycle oriented. I had one another SharedPreference on which this depend. That was getting false again and again.

Upvotes: 1

yoah
yoah

Reputation: 7230

I think you wanted to use if (!flag) (not flag) on the third line of the first code sample.

Upvotes: 0

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

remove the editor.clear(); from if condition. as clear will clear all the data from SharedPreference.

 if (flag) {
        SharedPreferences.Editor editor = prefs.edit();

        editor.putBoolean("checkFlag", true);
        editor.commit();
    }

Upvotes: 2

Related Questions