开发者

Serializing ArrayList android not working

UPDATE: After a bit of testing I've determined the file itself isnt being created, at least according to the file.exists check anyway. Any ideas?

Hi I'm trying to serialize an arraylist when my app is exited and read it back when its resumed. It doesnt seem to be creating the file.

Here is my code.

protected void onPause() {
    super.onPause();

    if(!myArrayList.isEmpty())
    {
        final String FILENAME = "myfile.bin";
        try{
            FileOutputStream fos;

            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

            //FileOutputStream fileStream = new FileOutputStream(FILENAME);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(myArrayList);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
 开发者_StackOverflow               e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
    }
}

@SuppressWarnings("unchecked")
    @Override
    protected void onResume() {
        super.onResume();

    File file = new File("myfile.bin");
    if(file.exists()){
        final String FILENAME="myfile.bin";
        try{
            FileInputStream fileStream = new FileInputStream(FILENAME);
            ObjectInputStream os = new ObjectInputStream(fileStream);
            myArrayList = (ArrayList<MyObject>)os.readObject();
            os.close();
        } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
        }
    }




}

Any ideas? My MyObject class implements serializable.


Got it to work by changing FileInputStream fileStream = new FileInputStream(FILENAME) to FileInputStream fileStream= openFileInput(FILENAME).


os.writeObject(myArrayList);
os.flush();
os.close();

Try os.close() immediately after writeObject, it should call flush() anyways.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜