【发布时间】:2020-04-19 02:34:13
【问题描述】:
我在 SharedPreferences 中遇到了一个非常奇怪的行为。我想知道我是否遇到了同步问题。
该应用似乎可以记住活动之间的偏好更改,但在我重新启动应用时不会。状态总是返回到我创建首选项的第一个实例。我遵循了几个示例、教程和 android 文档,它们都建议了类似的代码布局。我还观察了在使用调试器与我的代码交互时,preference.xml 文件是如何变化的,我确认它看起来像是更新了键值对。
我的模拟器是否会遇到同步问题?我尝试使用具有相同结果的 editor.apply() 方法和 editor.commit() 方法。 我发现解决我的问题的唯一方法是使用 editor.clear() 方法,但这感觉有点 hacky...
注意:请原谅变量名,我正在制作图鉴...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
【问题讨论】:
-
您向我们展示了谁获得了 sharedPreference,但没有向我们展示如何将内容添加到 sharedPreference 中,因为您仅在第一次添加内容之前不会满足的条件下添加它们共享偏好
-
啊,我现在意识到这还不清楚:toggleCatch 是在按下按钮时启动的。而在onCreate函数中,getStringSet会为pokemonCaught集合返回一个新的HashSet,这样toggleCatch函数中的编辑器就有一个Set来保存。我会将此添加到我的原始帖子中。