AMH
AMH

Reputation: 6451

SharedPreferences duplicate saved data

if I have ID = 5 and I want to save in SharedPreferences I got result 5,5 which is wrong the code I use is

String FavoritsKey = "com.test";
SharedPreferences preferences = getApplicationContext().getSharedPreferences("SpeakEgyptPreferences", Context.MODE_PRIVATE); 
preferences.edit().putString(FavoritsKey,  preferences.getString(FavoritsKey, "")+","+ selected.Id).apply();

For Example

the first time I want to save 5 => supposed to get string =",5" but I get ",5,5" an so on

How to solve the repeat

Upvotes: 0

Views: 211

Answers (1)

stealthjong
stealthjong

Reputation: 11093

I've interpreted your question as follows: You want to save the ID("5") to sharedpreferences, and when you retrieve it, it should be returned as ",5". Which means you can either save "5" in your sharedprefs and add the , on retrieval, or save the id including the comma (",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"

Or the other way around

/* 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"

Your code, however, did exactly as it should.

preferences.edit().putString(FavoritsKey,  preferences.getString(FavoritsKey, "")+","+ selected.Id).apply();

Lets look closer. In sharedPreferences, on key FavoritsKey, you store:

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...

Upvotes: 1

Related Questions