首页 > 解决方案 > 将不可序列化的位置对象保存到文件 Android

问题描述

我知道有几个线程接近这个主题,但我还没有看到完全解决我在这里寻找的答案——我需要保存由 Google Play 位置服务生成的位置对象的 ArrayList。位置对象是 Parcelable 但不是 Serializable。我试图通过传统的可序列化路线来保存它们,这当然失败了……见下面的代码。

    public static void saveArrayListLocations(Context context, ArrayList<Location> dataArrayList) {
    File folder = context.getFilesDir();
    File file = new File(folder, FILE_NAME);

    try {
        file.createNewFile();

        FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(dataArrayList);

        oos.close();
        fos.close();

    } catch (FileNotFoundException f) {
        System.out.println("File not found exception while saving");
    } catch (IOException i) {
        System.out.println("IO exception while saving");
    }
}

总是抛出 IOException。

所以,问题:有没有办法序列化 Location 对象?还是我应该考虑以某种方式使用他们的 Parcelable 功能?我对此有点陌生,我想知道使用 Map 或 Bundle 来打包数据是否会以某种方式工作?

标签: javaandroidioexceptionserializable

解决方案


推荐阅读