Search code examples
javaandroidarraylistandroid-sharedpreferences

SharedPreferences not to overwrite data


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]


Solution

  • 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.