android trying to save data using prefrences, does not work
I'm trying to learn how to use SharedPrences to save data.
In the test c开发者_如何转开发ode below, getString returns no value, instead of 'ted', but I cannot figure out why.
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
pre.edit().putString("label","ted");
pre.edit().commit();
String tr;
tr=pre.getString("label","no value");
of course both answers are right but dmon's solution is much more easer and short:)
its enough to rewrite your code like this :
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
pre.edit().putString("label","ted").commit();
String tr=pre.getString("label","no value");
Easy, edit()
creates an Editor. You're putting the value in one and committing in another one. Just save the edit()
return value in an Editor variable and call commit()
in that.
Could it be because you re-call the edit()
function? try this:
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = pre.edit();
ed.putString("label","ted");
ed.commit();
String tr;
tr=pre.getString("label","no value");
}
精彩评论