1

下面的代码有什么问题

我无法检索保存在 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", ""));
4

1 回答 1

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", "");

在此处输入图像描述

于 2013-05-25T02:04:14.610 回答