更新共享首选项中的列表

Updating list in shared preferences

在我的 android 应用程序中,我通过共享首选项中的 gson 存储了自定义 class 列表。 现在我的问题是我更改了 class WORD 中的代码,但我不知道如何将其应用到旧版应用程序“共享首选项”中的当前列表。感谢您的帮助!

我遇到了同样的问题。我的解决方法是用 try catch 包围你的错误,并从旧的对象中创建一个新的对象列表。然后保存您新创建的列表,以免再次发生。

          try {
                                        if (object.getNewMethod().equals("")) {
                                           wontHappenBecauseError();
                                        }
                                    }
                                    catch (Exception e) {
    
        //create new arraylist to save
                                        ArrayList<Object> updatedObjectList = new ArrayList<>();
    
        //loop through old objects
                                       for(Object oldObject: oldObjectsList){
    
        //for each, add an object to the new list from the attributes of the old list
                                           updatedObjectsList.add(new Object(oldObject.getAttribute, oldObject.getOtherAttribute);
}
    
    
        //save the new and improved list so it doesnt happen again
                                           Gson gson = new Gson();
                                           Type type = new TypeToken<ArrayList<Object>>(){}.getType();
                                           String json = gson.toJson(updatedObjectList,type);
                                           editor.putString("ObjectList",json);
    editor.commit();
                                       }