Skip to content Skip to sidebar Skip to footer

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 into SharedPreferences: StringBuilder stringBuilder = new StringBuilder(); for(String str: semesterArr

Solution 1:

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";
        editor.putString("current",text);
        if (!sharedPreferences.getString("current","").equals(sharedPreferences.getString("new","")))
        {
            editor.putString("new",sharedPreferences.getString("current","") + text );
            editor.commit();

        }
        editor.commit();

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 datais not updated  use sharedPreferences.getString("current","")  
else  your datais updated so use sharedPreferences.getString("new","")

Post a Comment for "How Can I Make Sharedpreferences To Update The Data Instead Of Overwriting The Data And Losing Part Of It?"