0

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);
    }

}
Psypher
  • 10,717
  • 12
  • 59
  • 83
Azcaq
  • 43
  • 1
  • 8
  • It is better to ask separate questions as multiple questions instead of combining them, so we can more accurately answer them individually. – Jon Adams Mar 27 '15 at 18:25

1 Answers1

1

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.

Community
  • 1
  • 1
Jonas Czech
  • 12,018
  • 6
  • 44
  • 65
  • "There is no need to explicitly save or load the preferences, as this is done automatically." As far as I know you have to call commit() or apply() to save preferences. – The incredible Jan Mar 28 '17 at 13:48