Marco C
Marco C

Reputation: 3213

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?

Upvotes: 1

Views: 3602

Answers (2)

Marco C
Marco C

Reputation: 3213

The problem was in depAdd and arrAdd that were not initializate.

Upvotes: 0

Ceetn
Ceetn

Reputation: 2736

  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, "");

Upvotes: 3

Related Questions