问题
I have application that gives me some string whenever I press the button and then save this value using sharedpreferences. However, I would like to limit this saving function, so it will save only the last three received strings.
The structure is of the following: String A String B String C
Next time when i click my button it will record the value into String A, while move the old String A to String B and old value of String B to String C, as well as, delete the old value of String C accordingly.
At the moment I'm not sure how its done.
Looking forward for your assistance.
回答1:
Try something like this:
//Obtain values
SharedPreferences prefs =
getSharedPreferences("PreferencesKey", Context.MODE_PRIVATE);
String stringA = prefs.getString("stringA", "defaultValue");
String stringB = prefs.getString("stringB", "defaultValue");
String stringC = prefs.getString("stringC", "defaultValue");
//Save values
SharedPreferences.Editor editor = prefs.edit();
editor.putString("stringA", lastValueSelected);
editor.putString("stringB", stringA);
editor.putString("stringC", stringB);
editor.commit();
Regards
回答2:
SharedPreferences sharedPreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
String B = pref.getString("A", null);
String C = pref.getString("B", null);
editor.putString("A", yourStringVariable);
editor.putString("B", B);
editor.putString("C", C);
editor.commit();
来源:https://stackoverflow.com/questions/34221276/sharedpreferences-replacement-of-data