Update settings in PreferenceActivity on Resume

In my application, some parameters can be changed until PreferenceActivity is open, and the problem I am facing is that addPreferencesFromResource is called in onCreate , so let's say I open PreferenceActivity then go to another screen, then do something that changes the settings , then press the back button to return to PreferenceActivity , and then some settings have not changed on the layout.

So, how could I reload all Preferences every time onResume (or onStart() ) is called without duplicating the layout?

+8
android reload sharedpreferences preferenceactivity
source share
2 answers

edit: this solution will only work for API 11 +.

I'm not sure I fully understand your problem, but you can add a call to recreate () in onResume activity, which, as I understand it, goes through the entire life cycle again.

To make sure that you only do this when there is actually dirty data, I would set a flag in SharedPreferences, which allows your activity to know in onResume () that it needs to be recreated.

  public void onResume(){ super.onResume(); SharedPreferences pref = getApplicationContext().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); if(pref.getBoolean("isDirtyPrefs", true)) recreate(); } 
+3
source share

I had a similar problem. Unable to find an easy way to do the PreferenceActivity update by itself, my solution was to add this to my PreferenceActivity:

 /** * Called when activity leaves the foreground */ protected void onStop() { super.onStop(); finish(); } 

This will reload the Prefs screen from SharedPreferences the next time it starts. Needless to say, this approach will not work if you want to return to the settings screen using the "Back" button.

+1
source share

All Articles