0

I am adding a set to SharedPreference. This is a static set from another class which processes some data and stores it in the set.

I then move on to another activity (Order Activity) where I display this set's information. The first time when I access the shared preference, I am able to get the correct details. For example name1, name2, name3.

I then leave this activity, go back to another activity, add another name and come back to this Order activity again. I am expecting to get name1, name2, name3, name4 this time. Instead I only get name4. The previous names seems deleted.

Order Activity inside onCreate Method

SharedPreferences prefItemName =
                this.getSharedPreferences("com.example..........", MODE_PRIVATE);
//CustomListAdapter is a class that is adding names to the static HashSet names
prefItemName.edit().putStringSet("name", CustomOrderListAdapter.names).apply(); 

for(String x : prefItemName.getStringSet("name", null)){
    Log.i("Name", x);
}

P.S: In the possible duplicate question, he is at least able to store the data all the data as long as he stays logged in. Mine doesn't save as long as I leave the activity. Ist is not the same issue.

cubeb
  • 557
  • 1
  • 5
  • 18
  • Possible duplicate of [Android SharedPreferences String Set - some items are removed after app restart](http://stackoverflow.com/questions/19949182/android-sharedpreferences-string-set-some-items-are-removed-after-app-restart) – Rick Sanchez Dec 21 '15 at 00:11
  • @Kushtrim It's not. Please read P.S. – cubeb Dec 21 '15 at 00:19

3 Answers3

2

Try to make a clear of your Editor as follows :

Editor edit = sp.edit();
edit.clear();

As JoseLSegura said...

A possible solution is to make a copy of the Set<String> returned by the SharedPreferences object

Example

Set<String> ss = new HashSet<String>(sharedPrefs.getStringSet("name", new HashSet<String>()));

Then with the Editor you make a clear as follows :

Editor edit = sp.edit();
edit.clear();
edit.putStringSet("name", ss);
edit.commit();

Hope it helps.

Community
  • 1
  • 1
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

For saving sharedpreferences doing like this:

SharedPreferences sp = PreferenceManager
            .getDefaultSharedPreferences(myActivityContent);
    Editor edit = sp.edit();
    edit.putString("mystring", mystring);

For loading sharedpreferences doing like this:

sharedpreferences sp = PreferenceManager
                    .getDefaultSharedPreferences(myActivityContent);
    String loadshare = sp.getString("mystring", sharemethod);
    if (!a2 .equals(sharemethod))
        //load data is successfully. 
    else
        //load data is unsuccessfully. 
shayan
  • 220
  • 2
  • 8
0

You are settings your data to the same location where your previous data was, so you overwrite it.

In this case you should first retrieve all the data and then save all the data.

geNia
  • 985
  • 9
  • 20