我有一个显示接口列表的列表视图,其中接口由两种类型的类实现:
1) 带日期的条目
2)按天分解条目的标题
我的问题是能够在应用程序打开/关闭时保存接口列表并将其加载到首选项中。据我了解,我需要使用接口适配器来序列化/反序列化接口列表。
我尝试按照教程进行操作,但出现错误
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);
}
列表视图中显示的列表:
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);
}
关闭应用程序时保存标题+条目的代码:
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();
}