首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从首选项保存和加载具有多种类型条目的列表视图的条目?

如何从首选项保存和加载具有多种类型条目的列表视图的条目?
EN

Stack Overflow用户
提问于 2019-07-11 03:49:21
回答 1查看 30关注 0票数 0

我有一个显示接口列表的列表视图,其中接口由两种类型的类实现:

1)带有日期的条目

2)按天拆分条目的表头

我的问题是,当应用程序打开/关闭时,是否能够将界面列表保存并加载到首选项中。据我所知,我需要使用interface adapter来序列化/反序列化接口列表。

我尝试按照教程进行操作,但遇到错误

代码语言:javascript
运行
复制
 Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

从下面的"loadCLEntries“函数中的"gson.fromJson(json,type)”行开始。下面是我的相关代码。

接口:

代码语言:javascript
运行
复制
public interface CallLogListViewItem {
    //These are so the list view can tell if an entry is a header or an entry
    public int getViewType();
    public View getView(LayoutInflater inflater, View convertView);
}

在listview中显示的列表:

代码语言:javascript
运行
复制
private static List<CallLogListViewItem> callLogEntries = new ArrayList<>();

当应用程序打开时,从首选项中加载条目+标题的代码:

代码语言:javascript
运行
复制
private static ArrayList<CallLogListViewItem> loadCLEntries() {
    SharedPreferences pref = App.getApp().getSharedPreferences("info", MODE_PRIVATE);
    String json = pref.getString("CallLogEntries", "[]");

    Type type = new TypeToken<ArrayList<CallLogListViewItem>>(){}.getType();

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(CallLogListViewItem.class, new InterfaceAdapter<>());
    Gson gson = builder.create();

    return gson.fromJson(json, type);
}

应用程序关闭时保存headers + entries的代码:

代码语言:javascript
运行
复制
private static void saveCLEntries() {
    //Save entries
    SharedPreferences pref = App.getApp().getSharedPreferences("info", MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    Gson gson = new Gson();
    String json = gson.toJson(callLogEntries, CallLogListViewItem.class);
    editor.putString("CallLogEntries", json);
    editor.apply();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-12 06:34:14

问题是我没有正确地保存接口列表。

在序列化列表时,我还需要使用接口适配器:

代码语言:javascript
运行
复制
private static void saveCLEntries() {
    //Save entries
    SharedPreferences pref = App.getApp().getSharedPreferences("info", MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();

    Type type = new TypeToken<ArrayList<CallLogListViewItem>>(){}.getType();

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(CallLogListViewItem.class, new InterfaceAdapter<>());
    Gson gson = builder.create();

    String json = gson.toJson(callLogEntries, type);
    editor.putString("CallLogEntries", json);
    editor.apply();
}

就是这样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56977684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档