java - SharedPreferences not working as expected, cannot read nor write preferences -
private void init() { sharedpreferences prefs = getsharedpreferences("data", context.mode_private); // set value record record = prefs.getint("record", 0); prefs.edit().commit(); } private void setrecord(int ) { sharedpreferences prefs = getsharedpreferences("data", context.mode_private); if(i > prefs.getint("record", 0)) prefs.edit().putint("record", i); prefs.edit().commit(); } private int getrecord() { int rec; sharedpreferences prefs = getsharedpreferences("data", context.mode_private); rec = prefs.getint("record", 0); prefs.edit().commit(); toast toast = toast.maketext(this, rec+"", toast.length_short); toast.show(); return rec; }
this code should set int , retrieve it, doesn't seem ever set it... can see why that?
think best call interface sharedpreferences.editor
edit preferences instead of using prefs.edit().putint("record", i);
. docs say...
modifications preferences must go through sharedpreferences.editor object ensure preference values remain in consistent state , control when committed storage.
if change setmethod
following should work...
private void setrecord(int ) { sharedpreferences prefs = getsharedpreferences("data", context.mode_private); sharedpreferences.editor editor = prefs.edit(); if(i > prefs.getint("record", 0)) editor.putint("record", i); editor.commit(); }
and guess calling above method setrecord
somewhere in code can't see being called anywhere in code snippet pasted.
Comments
Post a Comment