我正在项目中使用 SharedPreference
。
我知道可以使用 prefs.putStringSet()
来存储一个 Set<String>
。但是我的情况需要在 sharedPreference
中存储一个 Set<Set<String>>
。
我该如何实现这个需求?
我正在项目中使用 SharedPreference
。
我知道可以使用 prefs.putStringSet()
来存储一个 Set<String>
。但是我的情况需要在 sharedPreference
中存储一个 Set<Set<String>>
。
我该如何实现这个需求?
您可以使用Gson将Set<Set<String>>
转换为字符串,然后将其保存在sharepreference
中,但是没有直接的方法可以在sharepreference
中保存此类型。
Gson gson = new Gson();
String jsonObject = gson.toJson(your_set_variable);
editor.putString(KEY_PROJECTS, jsonObject );
editor.commit();
更新:如果您需要使用谷歌的Gson库,请将其添加到您的gradle依赖项中。
compile 'com.google.code.gson:gson:2.8.0'
使用SharedPreferences无法做到这一点,但是您可以将其保存到文件中。
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(set);
os.close();
fos.close();
编辑:您可以像这样加载它。
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
Set<Set<String>> set = (Set) is.readObject();
is.close();
fis.close();