если у меня 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 => должен получить строку =", 5", но я получаю ", 5,5" и т. д.
Как решить повтор
Ответ 1 · рейтинг 1 · stealthjong
Я интерпретировал ваш вопрос следующим образом: вы хотите сохранить идентификатор ("5") в общих настройках, и когда вы его получите, он должен быть возвращен как ",5". Это означает, что вы можете либо сохранить "5" в своих общих префах и добавить , при извлечении, либо сохранить идентификатор, включая запятую (",5").
/* 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...