SharedPreferences replacement of data

2019-03-07 08:09发布

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.

2条回答
Melony?
2楼-- · 2019-03-07 08:16

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

查看更多
唯我独甜
3楼-- · 2019-03-07 08:18
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();
查看更多
登录 后发表回答