Search code examples
androidloopssaveandroid-sharedpreferences

SharedPreferences replacement of data


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.


Solution

  • 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