sagar suri
sagar suri

Reputation: 4731

How to store Set<Set<String>> inside the SharePreferences?

I am using SharedPreference in my project.

I know sharedPreference can store Set<String> by using prefs.putStringSet(). But I have a situation where I need to store Set<Set<String>> in sharedPreference.

How can I achieve this?

Upvotes: 3

Views: 61

Answers (2)

Mosa
Mosa

Reputation: 381

you can use Gson to convert Set<Set<String>> to string then save it in sharepreference , but there is no direct way to save this type in sharepreference

Gson gson = new Gson();
    String jsonObject = gson.toJson(your_set_variable);

    editor.putString(KEY_PROJECTS, jsonObject );
    editor.commit();

Updated : this is the Gson library from google if you need to use it , add it in your gradle dependencies

compile 'com.google.code.gson:gson:2.8.0'

this library provided for you to convert any object you have to string and then convert this json string to your type you want , and stackoverflow and google had many and many of examples to using it

Upvotes: 3

peterrojs
peterrojs

Reputation: 67

You cannot do this with SharedPreferences but you can save the set to a file.

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(set);
os.close();
fos.close();

EDIT: You can then load it like this.

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
Set<Set<String>> set = (Set) is.readObject();
is.close();
fis.close();

Upvotes: 0

Related Questions