SharedPreferences replacement of data

旧巷老猫 提交于 2019-12-20 07:56:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!