0

I am trying to write a list with same values two times in the preferences and when I read it back I only get 1 result. Here is my SharedPreferences Code :

public void storeDeviceDetails(final ArrayList<String> deviceDetails) {
        SharedPreferences.Editor editor = context.getSharedPreferences("devicePrefs",Context.MODE_PRIVATE).edit();

        Set<String> set = new LinkedHashSet<>();
        set.addAll(deviceDetails);
        editor.putStringSet("deviceDetails", set);
        editor.apply();
    }

    public ArrayList<String> retrieveDeviceDetails() {
        SharedPreferences prefs = context.getSharedPreferences("devicePrefs", MODE_PRIVATE);
        ArrayList<String> details = null;

        Set<String> set = prefs.getStringSet("deviceDetails", null);

        if (set != null) {
            details = new ArrayList<>(set);
        }

        return details;
    }

I am writing it to List in 2 consecutive lines as -

MyPrefClass.storeDeviceDetails(myList);
MyPrefClass.storeDeviceDetails(myList);

And now in next line I do MyPrefClass.retrieveDeviceDetails(); I only get it as - [hero2lte, 7.0, hero2ltexx, SM-G935F, samsung]

Suraj Makhija
  • 1,376
  • 8
  • 16
MagdHo0506
  • 73
  • 8
  • 1
    Better provide a real [mcve] for us; instead of putting down parts of your code. – GhostCat Mar 20 '17 at 13:53
  • you are passing a list to a set and a set does not hold duplicate values – giorashc Mar 20 '17 at 13:55
  • Possible duplicate of [can i store two or more values with same key using SharedPreferences in android?](http://stackoverflow.com/questions/13623098/can-i-store-two-or-more-values-with-same-key-using-sharedpreferences-in-android) – denis_lor Mar 20 '17 at 13:57

1 Answers1

1
Set<String> set = new LinkedHashSet<>();

You're making a new set, so it's overwriting the old one completely.

Try getting the set that's already in SharedPreferences if it exists, and only make a new one if it doesn't. Something like this:

Set<String> set = prefs.getStringSet("deviceDetails", null);

if (set == null) {
    set = new LinkedHashSet<>();
}

Also, as mentioned in the comments, you're adding the same elements twice. Even if you were to fix it, a Set guarantees uniqueness, so they'd only be added once anyway.

Cruncher
  • 7,641
  • 1
  • 31
  • 65
  • Ok actually I am trying to save array list in shared prefs. How can i do this ? – MagdHo0506 Mar 20 '17 at 14:34
  • 2
    @Cruncher SharedPreferences doesn't store lists. If he needs that, he needs to use another storage mechanism. If set is sufficient for him, then your answer works. – Gabe Sechan Mar 20 '17 at 14:36
  • @GabeSechan Oh okay. Storing as a json array is probably the best thing then – Cruncher Mar 20 '17 at 14:37
  • Thank you all. I used this http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences instead of set and it worked :) – MagdHo0506 Mar 20 '17 at 14:52