如果我有ID = 5并且我想要保存在SharedPreferences
我得到结果5,5这是错误的我使用的代码是
String FavoritsKey = "com.test";
SharedPreferences preferences = getApplicationContext().getSharedPreferences("SpeakEgyptPreferences", Context.MODE_PRIVATE);
preferences.edit().putString(FavoritsKey, preferences.getString(FavoritsKey, "")+","+ selected.Id).apply();
例如
我第一次要保存5 =>应该得到string =",5"但我得到",5,5"等等
如何解决重复
答案 0 :(得分:1)
我已按如下方式解释您的问题:您希望将ID("5"
)保存到共享首选项,当您检索它时,应将其返回为",5"
。这意味着您可以在共享首选项中保存"5"
并在检索时添加,
,或者保存包含逗号(",5"
)的ID。
/* Storing the id */
String FavoritsKey = "com.test";
String valueToSave = "" + selected.ID; // we'll store "5" in sharedPreferences
Editor edit = preferences.edit();
edit.putString(FavoritsKey, valueToSave);
edit.commit(); //almost the same as apply, you can read the API docs if you want
/* Retrieving the id and prefix it */
String valueToRetrieve = preferences.getString(FavoritsKey, ""); // retrieve "5"
valueToRetrieve = "," + valueToRetrieve; // well prefix the "5" with "," for ",5"
或者相反
/* Storing the id with prefixed comma*/
String FavoritsKey = "com.test";
String valueToSave = "," + selected.ID; // we'll store ",5" in sharedPreferences
Editor edit = preferences.edit();
edit.putString(FavoritsKey, valueToSave);
edit.commit(); //almost the same as apply, you can read the API docs if you want
/* Retrieving the id with a prefixed comma */
String valueToRetrieve = preferences.getString(FavoritsKey, ""); // retrieve ",5"
但是,您的代码完全按照原样执行。
preferences.edit().putString(FavoritsKey, preferences.getString(FavoritsKey, "")+","+ selected.Id).apply();
让我们仔细看看。在sharedPreferences中,在密钥FavoritsKey
上,您可以存储:
preferences.getString(FavoritsKey, "")+","+ selected.Id)
//lets assume ",5" was stored initially
//outcome is ",5" + "," + 5 => thats ",5,5"
//and the next time another ",5" is added, and so on, etc...