Search code examples
androidpreferencessharedandroid-preferencessharedpreferences

Android ==> Preference?


my app crashes with a null pointer exception on the code below. i have an xml preference file under res/xml/defaults.xml Any idea why it's crashing?

public class Preference extends Activity {
    public Preference()
    {
    }

    public String getPreference(String key)
    {
                //it still crashes here
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
        String result = settings.getString(key,  null);
        return result;
    }
}

Solution

  • Preference files are not storead in project's /res/xml/defaults.xml

    They are stored on the device in your application folder something like

    /data/data/com.your.pkg/default.prefs
    

    Try do not specify the file name, as you will have some problems with the preference files, like this OP had here

    SharedPreferences preferences = PreferenceManager
                        .getDefaultSharedPreferences(context);
    

    Then you will probably have to query

    preferences.getString('weightPref', null);