SharedPreferences无法设置

时间:2013-05-25 02:02:14

标签: java android

以下代码有什么问题

我无法检索保存在SharedPreferences中的简单设置。 s1总是“”。这是我正在做的小错误>         SharedPreferences sp = getSharedPreferences(“MyTestPref”,0);

    String s = "Item1";
    sp.edit().putString("VAL", (s));
    sp.edit().apply(); //also tried commit
    String s1 = (sp.getString("VAL", ""));

1 个答案:

答案 0 :(得分:0)

应该是这样的:

String s = "Item1";
sp.edit().putString("VAL", (s));
sp.edit().commit(); //also tried commit
String s1 = (sp.getString("VAL", ""));

使用commit()而不是apply()

编辑:

final String PREFERENCE_NAME = "your_pref";
String s = "Item1";
SharedPreferences preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("VAL", s);
editor.commit();

String s1 = preferences.getString("VAL", "");

enter image description here