1

I am using parcel to cache Items in binary file. Everything was fine until I need to store into single ArrayList various type of objects:

        fout = new FileOutputStream(file);

        Parcel parcel = Parcel.obtain();
        ArrayList<Object> list = new ArrayList<Object>(items);
        Log.d(TAG, "write items to cache: " + items.size());
        parcel.writeList(list);
        byte[] data = parcel.marshall();
        fout.write(data);

But reading don't work properly:

fin = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fin.read(data);
Log.d(TAG, "file size: " + file.length());

Parcel parcel = Parcel.obtain();
parcel.unmarshall(data, 0, data.length);

ArrayList<Object> rawList = parcel.readArrayList(Object.class.getClassLoader());

I think problem is in Object classLoader, who can't create object for extended class.

Have any idea how I can easily fix this? Or maybe could somebody to give me advise for my task which is to cache ArrayList or Set into file with objects of type <? extends Object?>. Logcat:

08-20 12:16:52.200: D/ItemList(6637): writing data
08-20 12:16:52.200: D/ItemList(6637): write items to cache: 2
08-20 12:17:45.940: D/ItemList(6925): reading data
08-20 12:17:46.650: D/ItemList(6925): reading data
08-20 12:17:47.050: D/ItemList(6925): reading data
08-20 12:17:47.060: D/ItemList(6925): cache file found
08-20 12:31:18.050: D/ItemList(7349): file size: 760
08-20 12:17:47.060: D/ItemList(6925): founded items in cache: 0

More logcat:

08-20 12:49:02.930: D/ItemList(9241): file size: 1136
08-20 12:49:02.930: D/ItemList(9241): dataAvail(): 0
08-20 12:49:02.930: D/ItemList(9241): dataSize(): 1136
08-20 12:49:02.930: D/ItemList(9241): dataCapacity(): 1136
08-20 12:49:02.930: D/ItemList(9241): founded items in cache: 0

OK, I found it. You never read the data from the file:

fin = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];

All you do is create the input stream and allocate a byte buffer.

EDIT Add more code about how to unmarshall the Parcel

Parcel parcel = Parcel.obtain();
parcel.unmarshall(data, 0, data.length);
parcel.setDataPosition(0); // Set the position in the parcel back to the beginning
                           //  so that we can read the stuff out of it
ArrayList<Object> rawList = parcel.readArrayList(Object.class.getClassLoader());
4

1 回答 1

2

好的,我找到了。您从未从文件中读取数据:

fin = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];

您所做的就是创建输入流并分配一个字节缓冲区。

编辑添加更多关于如何解组包裹的代码

Parcel parcel = Parcel.obtain();
parcel.unmarshall(data, 0, data.length);
parcel.setDataPosition(0); // Set the position in the parcel back to the beginning
                           //  so that we can read the stuff out of it
ArrayList<Object> rawList = parcel.readArrayList(Object.class.getClassLoader());
于 2012-08-20T09:25:56.597 回答