Search code examples
javaandroidsharedpreferences

SharedPreferences doesn't update preferences immediately. Requires app restart


I am trying to update the app layout based on user preference. After the preference is made, the app requires restart for the preference to come into effect. I want it to happen immediately without restart. Here is my Activity class.

public class MainActivity extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainactivity);
    SharedPreferences getPrefs = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());     
    theme  = getPrefs.getString("themelist", "0");
    switch(theme){
    case "0":
        setContentView(R.layout.mainactivity);
        break;
    case "1":
        setContentView(R.layout.mainactivity_black);
        break;
    }       

    initialize();
    setClickListeners();        
}

Solution

  • Its gotta do with the lifecyle of the MainActivity. Problem was that onCreate() method doesn't get called when the main activity returns to focus after preferences are made. So moving the setting of layout to the onStart() or onResume() method solves my problem.