rootpanthera
rootpanthera

Reputation: 2771

SharedPreferences not working properly

Please see code below

@Override
protected void onStop() {
    super.onStop();
    SharedPreferences prefs = getSharedPreferences("screenPref", Context.MODE_PRIVATE);
    SharedPreferences.Editor edit = prefs.edit();
    edit.putString("active_screen", activeScreenText);

    if(edit.commit()){

        Log.i("APP", "SAVED!!"); // LOGCAT Always execute this piece of code

    }
}


// onCreate
SharedPreferences pref = getSharedPreferences("screenPref", Context.MODE_PRIVATE);
    activeScreen.setSummary(pref.getString("active_screen", "Never"));

When user choses an option from ListPreference, that option is saved in "activeScreenText" variable. If i restart the application (Home button, and navigate back to it) it works perferct. String is loaded and summary for this preference is set. But if android kills my app (or if i FORCE CLOSE it ), then this change is not persistent. I get "Never" everytime my app goes out of memory, but corresponding list preference stays at the same value.

(I have few options in listpreference and i would like to set summary, which value is current chosen. )

For example:

ListPreference: -Never -Choice1 -Choice2 -Choice3

Let's say i choose Choice3. Summary is set correctly when i choose value. If i exit application and restart it again, it loads perferct. If my app is force closed or killed by android, then Choice3 is still selected but my summary value is default ( Never ).

What Am I doing wrong?

Upvotes: 1

Views: 111

Answers (3)

Eugene Popovich
Eugene Popovich

Reputation: 3473

Save your values to sharedpreferences right after edit, not in the onStop() method

Upvotes: 1

s.d
s.d

Reputation: 29436

OnStop() is not guaranteed to be called. Never rely on it for saving important data. As documentation says:

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

Also, why are you saving preferences every time in such a way ? Save it when user interacts with it or just follow Android's settings pattern.

Upvotes: 1

Vipul Purohit
Vipul Purohit

Reputation: 9827

You can try to move you onStop() code to onPause() event. Maybe this will solve you problem.

Upvotes: 0

Related Questions