Skip to content
Advertisement

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

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

JavaScript

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!

Advertisement

Answer

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 :

JavaScript

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 :

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement