16

How can I control which file should be used by a PreferencesFragment for reading and writing settings? I can't find anything about that in the docs. If that can't be controlled via code or XML resources, are there any guarantees, what the file is called, so I can open it explicitly using

Activity.getSharedPreferences(String name, int mode)

Thanks.

Chris
  • 3,192
  • 4
  • 30
  • 43
  • This may be useful for copying the preference file after writing to it http://stackoverflow.com/a/25585711/1815624 – CrandellWS Dec 22 '16 at 08:18

1 Answers1

47

You have to manipulate the PreferenceManager of the SettingsFragment. This is what it looks like

// Constants
//--------------------------------------------------------------------------
private final static String TAG = SettingsFragment.class.getName();
public final static String SETTINGS_SHARED_PREFERENCES_FILE_NAME = TAG + ".SETTINGS_SHARED_PREFERENCES_FILE_NAME";

// Life-cycle
//--------------------------------------------------------------------------
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate()");

    // Define the settings file to use by this settings fragment
    getPreferenceManager().setSharedPreferencesName(SETTINGS_SHARED_PREFERENCES_FILE_NAME);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);
}

Then you can access this settings file outside of the fragment like this:

SharedPreferences preferences = getActivity().getSharedPreferences(
        SettingsFragment.SETTINGS_SHARED_PREFERENCES_FILE_NAME,
        Context.MODE_PRIVATE);
Maxr1998
  • 1,179
  • 14
  • 22
Chris
  • 3,192
  • 4
  • 30
  • 43
  • 6
    Using `PreferenceFragmentCompat`, I had to define the settings file in the `onCreatePreferences`method (instead of in onCreate) for it to work. – TouchBoarder Jan 11 '16 at 07:37