How do I get preferences to work in Android? How do I get preferences to work in Android? android android

How do I get preferences to work in Android?


I'm still working all this out myself, but (somewhat adapted from my version) I think your Preferences class only needs to do the following:

public class Preferences extends PreferenceActivity {    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // load the XML preferences file        addPreferencesFromResource(R.xml.preferences);    }}

Then in your main class, you can refer to the preferences:

public class DrinkingBuddy extends Activity                            implements OnSharedPreferenceChangeListener {    private int weight;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);        // register preference change listener        prefs.registerOnSharedPreferenceChangeListener(this);        // and set remembered preferences        weight = Integer.parseInt((prefs.getString("weightPref", "120")));        // etc    }    // handle updates to preferences    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {        if (key.equals("weightValues")) {            weight = Integer.parseInt((prefs.getString("weightPref", "120")));        }        // etc    }}

The saving of preference updates is handled for you.

(Not too sure about public/private declarations!)


You are requesting probably two different set of preference files.

Make sure you store the ListPreference values in the same files.Start up adb roll to the cd /data/data/com.your.package and look for folders and files of type preferences.

I think the bug is that you specify a different file than the one the setting has been saved too:

Try changing this:

SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

to

SharedPreferences preferences = PreferenceManager                .getDefaultSharedPreferences(context);

Then you will probably have to query only

preferences.getString('weightPref', null);

Also you do not need the Editor. The preferences are saved automatically.


For most apps, it is most convinient to use the default shared preferences. You can get from anywhere in you app them with:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

You can save new variables into it with:

sp.edit().putString("var_name", "var value".apply();