SharedPreference problem in android
public class WordDisplay extends Activity {
private int level;
private int group;
private int set;
private WordDisplay mContext=this;
private int l;
private int g;
private in开发者_JS百科t s;
SharedPreferences preferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wordset);
set_Word_Display_Event();
loadPreferences();
}
protected void loadPreferences() {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
l= preferences.getInt("Level", 0);
g=preferences.getInt("Group", 0);
s= preferences.getInt("Set", 0);
// Log.d("lll"," - "+preferences.getInt("level",0));
}
@Override
protected void onStop() {
super.onStop();
savePreferences(this.level,this.group,this.set);
}
protected void savePreferences(int level, int group, int set) {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
//preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Level", l);
editor.putInt("Group", g);
editor.putInt("Set", s);
editor.commit();
//return getPreferences(s).getInt("Set", 0);
}
}
Here, my data could not persist properly. what is the wrong my code. please give good convenience. Comments of the above code, Also checking but could not any effect.
First, onStop()
"might" never be called (see Activity life cycle), practice is to save your data in the onPause()
method.
Maybe try to add more logs to see what's going on?
- is
onStop()
called? - what are the saved / loaded values?
- etc.
Try it with a final string constant in your class:
public static final String PREFS_NAME = "MyPreferences";
and then always use the member function:
getSharedPreferences(PREFS_NAME, 0);
normally there is no magic to do.
http://developer.android.com/guide/topics/data/data-storage.html#pref
精彩评论