How can I make SharedPreferences to update the data instead of overwriting the data and losing part of it?

Tags: , , ,

I’m using the following piece of code to save an ArrayList<String> into SharedPreferences:

StringBuilder stringBuilder = new StringBuilder();

    for(String str: semesterArray) {

    SharedPreferences sharedPreferences = getSharedPreferences("PREFERENCES", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("semesterArray", stringBuilder.toString());

This is somewhat getting the job done since it saves the ArrayList<String> as intended and when the app is re-launched the Semesters that were added are still stored in the ArrayList<String> as I want them to be. But if I add more Semesters after re-launching the app, the Semesters that were saved are overwritten and I lose the previously saved Semesters. Is there a way SharedPreferences can be updated instead of overwritten? If not, in what direction should I move to store these Semesters? Thanks for the help!


As i mentioned in my comment using sharedPrefences to update or insert new values is not a good practice , but i will give you a solution if you want to use sharedPrefences

what you can do is :

  1. create prefrence called current to save the value of your string
  2. create another prefrence called new , to save the new data after checking that it’s not equal to the current.

you will end with something like this code :

 sharedPreferences = getSharedPreferences("shared",MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String text = "first text";
        if (!sharedPreferences.getString("current","").equals(sharedPreferences.getString("new","")))
            editor.putString("new",sharedPreferences.getString("current","") + text );


Result after first save : sharedPreferences.getString(“current”,””) will return “some text” and sharedPreferences.getString(“new”,””) will return “”

Result after changing “first Text” to ” new text” : sharedPreferences.getString(“current”,””) will return “new text” and sharedPreferences.getString(“new”,””) will return “first text new text”

how to use it :

  if sharedPreferences.getString("new","") equals ""
your data is not updated  use sharedPreferences.getString("current","")  
else  your data is updated so use sharedPreferences.getString("new","")

Source: stackoverflow