Search code examples
androidandroid-sharedpreferences

Place a non String Data Type in putStringSet SharedPreferences Android


It was an array list at first then I tried changing it into a set so I can place it at putStringSet. But yeah.. It doesn't have a String Datatype

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

The RecordData is a class that I created.

I suck.


Solution

  • you can use GSON library.. try this For saving and loading shared preferences data:

    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;
           }
    

    Also place this in your Gradle file:

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