保存数据没有问题。但是在加载数据时出现此错误信息

A/libc﹕ Fatal signal 11 (SIGSEGV), code 1, fault addr 0xa3907e44 in tid 2407 (myapplication)

此方法使用Google的GSON库保存数据。该类是适配器的一部分,每次用户在对话框中按下按钮时都将调用该类。
 public int saveListToFile(UserData data, Context context) {

            itemsData.add(data);
            notifyItemInserted(itemsData.size()-1);

        String filename = "colors";
        File file = new File(context.getFilesDir(), filename);
        try {
            BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file, true));
            Gson gson = new Gson();
            Type type = new TypeToken<List<UserData>>() {}.getType();
            String json = gson.toJson(itemsData, type);
            buffWriter.append(json);
            buffWriter.newLine();
            buffWriter.close();
        } catch (IOException e) {
            return -1;
        }
        return 0;
    }

此方法使用Google的GSON库加载数据。此方法还会导致应用崩溃,导致出现上述错误
    public int readCurrentList() {
            String filename = "colors";
            File file = new File(getFilesDir(), filename);

                try {
                    BufferedReader buffReader = new BufferedReader(new FileReader(file));
                    String line;
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<UserData>>() {}.getType();
                    while ((line = buffReader.readLine()) != null) {
                        itemsData.addAll((java.util.Collection<? extends UserData>) gson.fromJson(line, type));
                    }
                    buffReader.close();
                } catch (IOException e) {
                    return -1;
            }

            return 0;
        }

最佳答案

我和你有同样的问题。我花了几分钟才意识到:我正在让Gson将JSON转换为抽象对象列表。由于您无法实例化抽象类,因此当然将不起作用,尽管看到SIGSEGV而不是更好的异常有点令人惊讶。
UserData是抽象类吗?在那种情况下,您要么不得不改用另一个类,要么可能是https://stackoverflow.com/a/9106351/467650中描述的解决方案。

09-30 14:44
查看更多