每次启动应用程序时都会重置 SharedPreferences
SharedPreferences is being reset every time the app started
我的 MainActivity.java:
我有这个代码
SharedPreferences ids = getSharedPreferences(AddedIds, Context.MODE_PRIVATE);
SharedPrefernces.Editor editor = ids.edit();
if (ids.getStringSet(AddedIds, id).isEmpty()) {
Set<String> id = new HashSet<String>();
editor.putStringSet(AddedIds, id);
editor.apply();
}
此代码正在检查 Set<String>
是否存在于 SharedPreferences
中。如果不是,则将 Set<String>
添加到 SharedPreferences
.
问题是每当我打开应用程序时,代码都会被激活,尽管它存在于 SharedPreferences
中。
您的代码所做的是检查存储在 SharedPreferences
中的集合是否为空。
您想要的是使用 contains method 检查字段是否存在。所以应该是
SharedPreferences ids = getSharedPreferences(AddedIds, Context.MODE_PRIVATE);
SharedPrefernces.Editor editor = ids.edit();
if (!ids.contains(AddedIds)) {
Set<String> id = new HashSet<String>();
editor.putStringSet(AddedIds, id);
editor.apply();
}
我相信 id 是您在 stringset 中搜索的字符串。将您的代码更改为以下内容。
Set<String> set = ids.getStringSet(AddedIds, null);
Boolean keyfound = false;
if ( set != null){
for (String key : set){
if(key.equals(id)){
keyfound = true;
break;
}
}
if(!keyfound){
set.add(id);
editor.putStringSet(AddedIds, set);
editor.apply();
}
}
else{
set = new HashSet<String>();
set.add(id);
editor.putStringSet(AddedIds, set);
editor.apply();
}
我的 MainActivity.java:
我有这个代码 SharedPreferences ids = getSharedPreferences(AddedIds, Context.MODE_PRIVATE);
SharedPrefernces.Editor editor = ids.edit();
if (ids.getStringSet(AddedIds, id).isEmpty()) {
Set<String> id = new HashSet<String>();
editor.putStringSet(AddedIds, id);
editor.apply();
}
此代码正在检查 Set<String>
是否存在于 SharedPreferences
中。如果不是,则将 Set<String>
添加到 SharedPreferences
.
问题是每当我打开应用程序时,代码都会被激活,尽管它存在于 SharedPreferences
中。
您的代码所做的是检查存储在 SharedPreferences
中的集合是否为空。
您想要的是使用 contains method 检查字段是否存在。所以应该是
SharedPreferences ids = getSharedPreferences(AddedIds, Context.MODE_PRIVATE);
SharedPrefernces.Editor editor = ids.edit();
if (!ids.contains(AddedIds)) {
Set<String> id = new HashSet<String>();
editor.putStringSet(AddedIds, id);
editor.apply();
}
我相信 id 是您在 stringset 中搜索的字符串。将您的代码更改为以下内容。
Set<String> set = ids.getStringSet(AddedIds, null);
Boolean keyfound = false;
if ( set != null){
for (String key : set){
if(key.equals(id)){
keyfound = true;
break;
}
}
if(!keyfound){
set.add(id);
editor.putStringSet(AddedIds, set);
editor.apply();
}
}
else{
set = new HashSet<String>();
set.add(id);
editor.putStringSet(AddedIds, set);
editor.apply();
}