【发布时间】:2021-01-18 23:53:33
【问题描述】:
在我的 android 应用程序中,我通过 gson 在共享首选项中存储了一个自定义类 List 的列表。 现在我的问题是我更改了 WORD 类中的代码,但我不知道如何将其应用于旧版本应用程序的“共享首选项”中的当前列表。感谢您的帮助!
【问题讨论】:
-
您可以编辑您的帖子以包含相关代码和您尝试过的内容吗?
标签: android gson sharedpreferences
在我的 android 应用程序中,我通过 gson 在共享首选项中存储了一个自定义类 List 的列表。 现在我的问题是我更改了 WORD 类中的代码,但我不知道如何将其应用于旧版本应用程序的“共享首选项”中的当前列表。感谢您的帮助!
【问题讨论】:
标签: android gson sharedpreferences
我遇到了同样的问题。我的解决方法是用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();
}
【讨论】: