Search code examples
androidsharedpreferences

Android 4.2 SharedPreferences returns wrong value


I'm trying to get some values from SharedPreferences, and I write it in this code;

            SharedPreferences prefs = getPreferences(MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt(MainActivity.OBSDONE, observationer);
            editor.putInt(MainActivity.COROBS, korrekte);
            editor.commit();

I got the data from the SharedPreferences-file by pulling it off the Virtual Device, and the data looks correct.

When I try to pull it out from SharedPreferences with;

    SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    int obs = prefs.getInt(OBSDONE,0);
    int cor = prefs.getInt(COROBS,0);

it returns 0 to both values?


Solution

  • Use this

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    prefs.edit().putInt(MainActivity.OBSDONE,observationer).apply();
    prefs.edit().putInt(MainActivity.COROBS, korrekte).apply();