9

In my app, some settings can possibly be changed while the PreferenceActivity is not open, and an issue I'm running into is that addPreferencesFromResource is called in onCreate, so say, I open the PreferenceActivity, then go to another screen from there, then do something that changes the settings, then hit the back key to go back to the PreferenceActivity, then certain settings have not changed on the layout.

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

Reed
  • 14,703
  • 8
  • 66
  • 110

2 Answers2

3

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

Im not sure I fully understand your problem, but you could add a call to recreate() into the onResume of the activity which from my understanding has the activity go through the entire lifecycle again.

In order to make sure that you only do this when there is in fact dirty data, I would set a flag in the SharedPreferences that lets your activity know in the 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();
        }
JoeLallouz
  • 1,338
  • 1
  • 10
  • 14
  • Thank you. I haven't tested it yet, but looks like it will work. I wasn't aware of the recreate() command I had been looking in PreferenceActivity and PreferenceManager. But thank you, as that is exactly what I wanted. – Reed Sep 19 '11 at 22:41
  • I would recommend that you test out the logic as this could loop over and over since onResume will be called in the life cycle process and if the developer does not set the preference or it not there, than it will default to true and loop. – Ray Hunter Oct 06 '14 at 22:48
1

I had a similar problem. Failing to find a simple way to make my PreferenceActivity refresh itself, my solution was to add this to my PreferenceActivity:

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

This will cause the Prefs screen to reload from SharedPreferences next time it is started. Needless to say, this approach won't work if you want to be able to go back to your preferences screen by using the back button.

Anders
  • 1,401
  • 3
  • 16
  • 20
  • I considered that, but my `PreferenceActivity` starts other Activities, and it would've just been too much of a hassle to override `onKeyDown` and `onKeyUp` in those activities to start my `PreferenceActivity` again. Thank you for the suggestion, though. – Reed Oct 05 '11 at 21:44