Search code examples
javaandroidsharedpreferencespreferencefragment

Java - Android PreferenceFragment save and load preferences


I created a PreferenceFragment. How I can save the changed preferences and load by app restart? My second question: How I can get preference values from another class?

My PrefsActivity

public class PrefsActivity extends ActionBarActivity {
    public static PrefsFragment mPrefsFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FragmentManager mFragmentManager = getFragmentManager();
        FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
        mPrefsFragment = new PrefsFragment();
        mFragmentTransaction.replace(android.R.id.content, mPrefsFragment);
        mFragmentTransaction.commit();
    }
}

And my PrefsFragment

public class PrefsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }

}

Solution

  • To read preferences, use the following in your other Activity:

    SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
    

    Then, to read the preferences, use:

    String sEmailAddr = spref.getString("email", "");
    

    The first argument is the 'key' you want to get, and this should be defined in the XML file of the perferences (R.xml.settings in your case). The second argument is what should be returned when there is no such key.

    Other types of Preference work in a similar way. To get a boolean, set by a checkbox:

    boolean showEmail = spref.getBoolean("show_emails", true);
    

    There is no need to explicitly save or load the preferences, as this is done automatically.

    There is more information in the docs. You should also initialize the default values for the preferences, as described here.