Archie.bpgc
Archie.bpgc

Reputation: 24012

Android: Shared Preference value doesn't change even after committing

In an Activity_A, i have:

public static final String PREFS_NAME = "MyPrefsFile";

SharedPreference settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();

in Activity_B i have:

//changing the previously added **city** value
SharedPreferences settings = getSharedPreferences(Activity_A.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("city", myCity);
editor.commit();

in Activity_C i have:

SharedPreferences settings = getSharedPreferences(Activity_A.PREFS_NAME, 0);
String city = settings.getString("city", "default");
//here i am getting the previous value of **city**, not the updated 1 from Activity_B

But once i restart the application then it gives the correct value.

What am i doing wrong?

Thank You

Upvotes: 0

Views: 2088

Answers (1)

Rolf ツ
Rolf ツ

Reputation: 8781

In Activity C where you want to show the value, when do you get the value from the SharedPreferences?

You should get the SharedPreferences values in the onResume method i think because if you do this in the onCreate method no changes will be there if you co back to Activity C.

This is because the onCreate method will only be called once the Activity is first created. When you navigate back (away) from Activity C it goes on the backstack and is later restored using the onRestart or onResume. This means that the onCreate method is not called again.

So i suggest that you do the getting from the SharedPreferences in the onResume method.

Activity lifecylce: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

I'm right?

Rolf

Upvotes: 2

Related Questions