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
In
Activity Cwhere you want to show the value, when do you get the value from theSharedPreferences?You should get the
SharedPreferencesvalues in theonResumemethod i think because if you do this in theonCreatemethod no changes will be there if you co back toActivity C.This is because the
onCreatemethod will only be called once theActivityis first created. When you navigate back (away) fromActivity Cit goes on thebackstackand is later restored using theonRestartoronResume. This means that theonCreatemethod is not called again.So i suggest that you do the getting from the
SharedPreferencesin theonResumemethod.Activity lifecylce: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
I’m right?
Rolf