getPreferences always returns default value

前端 未结 1 1024
暖寄归人
暖寄归人 2021-01-21 02:15

I have set up a PreferenceFragment with two boolean preferences. The Fragment works fine and the settings are stored when the app is closed and reopene

相关标签:
1条回答
  • 2021-01-21 02:49

    After fiddling around with this for some hours I figured out the reason why this didn't work for me. There are several SharedPreferences inside a single app, which I didn't realize. This means that (1) Activity.getPreferences(int mode), (2) Context.getSharedPreferences(String name, int mode) and (3) PreferenceManager.getDefaultSharedPreferences(Context context) returns different instances of SharedPreferences.

    In my case, the solution was to use PreferenceManager.getDefaultSharedPreferences(Context context). This is because I use a custom library for backwards compatibility of PreferenceFragment. This library writes to the default preferences file.

    From the docs:

    PreferenceManager.getDefaultSharedPreferences(Context context)

    Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

    So this is preferences for the given Context or Activity at any time using the default filename for preferences. This is a static instance of the PreferenceManager class.

    Context.getSharedPreferences(String name, int mode)

    Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

    Using this method you can distinguish between several preference files, using the String argument.

    Activity.getPreferences(int mode)

    Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

    This method calls directly to the previous one like this: getSharedPreferences(getLocalClassName(), mode). Hence it points to a file depending on the name of the Activity.

    Other related questions (possible duplicates):

    Difference between getDefaultSharedPreferences and getSharedPreferences

    PreferenceManager.getDefaultSharedPreferences() vs getPreferences()

    0 讨论(0)
提交回复
热议问题