简体   繁体   中英

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?

Use this

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

This worked for me:

pref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());

Or if u only have a context:

pref = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM