我有一个显示接口列表的列表视图,其中接口由两种类型的类实现:
1)带有日期的条目
2)按天拆分条目的表头
我的问题是,当应用程序打开/关闭时,是否能够将界面列表保存并加载到首选项中。据我所知,我需要使用interface adapter来序列化/反序列化接口列表。
我尝试按照教程进行操作,但遇到错误
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)”行开始。下面是我的相关代码。
接口:
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中显示的列表:
private static List<CallLogListViewItem> callLogEntries = new ArrayList<>();当应用程序打开时,从首选项中加载条目+标题的代码:
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的代码:
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();
}发布于 2019-07-12 06:34:14
问题是我没有正确地保存接口列表。
在序列化列表时,我还需要使用接口适配器:
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();
}就是这样。
https://stackoverflow.com/questions/56977684
复制相似问题