creativecoder
creativecoder

Reputation: 1540

How to store Integer Hashset in SharedPreference?

It says wrong 2nd argument type required set String.

Set<Integer> hs = pref.getStringSet("set", new HashSet<Integer>());
hs.add(String.valueOf(hs.size()+1));
SharedPreferences.Editor edit = pref.edit();
edit.putStringSet("set", hs);
edit.commit();

Upvotes: 0

Views: 1818

Answers (3)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29794

It says wrong 2nd argument type required set String.

It's because you're incorrectly using the getStringSet with the following code:

Set<Integer> hs = pref.getStringSet("set", new HashSet<Integer>());

it should be like this:

Set<String> hs = pref.getStringSet("set", new HashSet<String>());

You should recognize the method signature which is clearly telling that the method is giving you a string set with getStringSet.

Upvotes: 0

Dhiraj Sharma
Dhiraj Sharma

Reputation: 4869

Use Gson

implementation 'com.google.code.gson:gson:2.8.5'

Gson helps to convert custom object to string & string to custom object. So you can convert set to string save to shared pref. And later get string from shared pref and convert to set.

To save

Set<Integer> mySet = new HashSet<>();
String json = new Gson().toJson(mySet);
//Save json to shared pref

Then to retrieve

//get json from shared preference saved earlier
Set<Integer> mySet2 = new Gson().fromJson(json, new TypeToken<Set<Integer>>() {
            }.getType());

Upvotes: 0

sneharc
sneharc

Reputation: 513

You can do the conversion and store it in SharedPreferences like this,

SharedPreferences preferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
    Set<Integer> integerHashSet = new HashSet<>();
    integerHashSet.add(1);
    integerHashSet.add(2);

    //convert String HashSet to Integer HashSet
    Set<String> stringHashSet = new HashSet<>();
    for (Integer i : integerHashSet) {
        stringHashSet.add(String.valueOf(i));
    }

    preferences.edit().putStringSet("set", stringHashSet).commit();
    Set<String> stringSet = preferences.getStringSet("set", new HashSet<String>());
    Set<Integer> integerSet = new HashSet<>();

    //Convert it back
    for (String str : stringSet) {
        integerSet.add(Integer.parseInt(str));
    }

    //now user integerSet

Upvotes: 2

Related Questions