将非字符串数据类型放入 putStringSet SharedPreferences Android

Place a non String Data Type in putStringSet SharedPreferences Android

起初它是一个数组列表,然后我尝试将其更改为一个集合,这样我就可以将它放在 putStringSet 中。但是是的..它没有字符串数据类型

    Set<RecordData> set = new HashSet<>(dataList);
      SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putStringSet("recordlists", set);

RecordData 是我创建的class。

我很烂

您可以使用 GSON 库.. 试试这个保存和加载共享首选项数据:

public static void saveSharedPreferencesLogList( Set<RecordData> record) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            SharedPreferences.Editor prefsEditor = preferences.edit();
            Gson gson = new Gson();
            String json = gson.toJson(record);
            prefsEditor.putString("myJson", json);
            prefsEditor.commit();
        }


        public static Set<RecordData> loadSharedPreferencesLogList() {
            Set<RecordData> record = new HashSet<>(dataList);

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            Gson gson = new Gson();
            String json = preferences.getString("myJson", "");
            if (json.isEmpty()) {
                record = new Set<RecordData>();
            } else {
                Type type = new TypeToken<Set<RecordData>>() {
                }.getType();
                record = gson.fromJson(json, type);
            }
            return record;
       }

同时将其放入您的 Gradle 文件中:

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