Reload SharedPreferences on resume? (or how to refresh/reload activity)

一个人想着一个人 提交于 2020-01-23 01:55:49

问题


How can I reload SharedPreferences when I resume from one activity to another? If I resume, it is possible that user has changed the settings. Is it possible to reload SharedPreferences or do I need to refresh/reload activity. And if, then how?


回答1:


There is no difference in how you get and set SharedPreferences normally and from doing so in onResume. What you will need to do in addition to getting the most recent preferences, is update any objects you have in the Activity that use preference values. This will ensure your Activity is working with the most recent values.

A simple example:

protected void onResume() {
    super.onResume();
        getPrefs();

    //...Now update your objects with preference values         
}

private void getPrefs() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String myPref = prefs.getString("myPref", "");
}


来源:https://stackoverflow.com/questions/5364099/reload-sharedpreferences-on-resume-or-how-to-refresh-reload-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!