Search code examples
androidpreferences

How To Load SharedPreferences


I want to load the user preferences when I start the application. The preferences are correctly stored, because when I start the PreferenceActivity from the main activity it will load the saved value. The problem is that in the main activity I'm not able to load the preferences with this method:

private void updateFromPreferences() {
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager
    .getDefaultSharedPreferences(context);

depAdd = prefs.getString(Preferences.PREF_DEP_ADD, "");
arrAdd = prefs.getString(Preferences.PREF_ARR_ADD, "");
}

Is there something wrong?


Solution

    1. Use a public static final String so you will always access the right/same file

      public static final String PREFS_FILE = "MyPrefs";

    2. Create new SharedPreferences object

      SharedPreferences sharedpreferences = getSharedPreferences(PREFS_FILE, 0);

    3. Get whatever value you want from the preferences file

      depAdd = sharedpreferences.getString(Preferences.PREF_DEP_ADD, "");