How to save List to SharedPreferences?

It only possible to use primitive types because preference keep in memory. But what you can use is serialize your types with Gson into json and put string into preferences:

private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);

private static SharedPreferences.Editor editor = sharedPreferences.edit();
    
public <T> void setList(String key, List<T> list) {
    Gson gson = new Gson();
    String json = gson.toJson(list);
    
    set(key, json);
}

public static void set(String key, String value) {
    editor.putString(key, value);
    editor.commit();
}

Extra Shot from below comment by @StevenTB

To Retrive

 public List<YourModel> getList(){
    List<YourModel> arrayItems;
    String serializedObject = sharedPreferences.getString(KEY_PREFS, null); 
    if (serializedObject != null) {
         Gson gson = new Gson();
         Type type = new TypeToken<List<YourModel>>(){}.getType();
         arrayItems = gson.fromJson(serializedObject, type);
     }
}

Leave a Comment