序列化一个ArrayList [英] Serializing an ArrayList

查看:94
本文介绍了序列化一个ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个安卓游戏,我希望能够暂停,即使用户想要返回到主菜单或活动得到由系统杀死了比赛。似乎的onSaveInstanceState不给我一大堆控制何时我能读捆回来,再加上从我所知道的,包是仅适用于很短的时间好。所以我想序列化我有几个的ArrayList,然后阅读他们回来。我没有得到任何编译错误也不该程序崩溃。但是,无论是永远不会被写入或从未得到的数据读取。我不知道哪一个。我的serializeData方法被称为在的onDestroy和deserializeData从的onCreate调用。这里是我的code的写入和读取数据:

I'm trying to write an Android game and I would like to be able to pause the game even if the user wants to return to the main menu or the activity gets killed off by the system. onSaveInstanceState doesn't seem to give me a whole lot of control as to when I can read the bundle back, plus from what I can tell, the bundle is only good for short periods of time. So I want to serialize a few ArrayLists that I have, then read them back. I don't get any compile errors nor does the program crash. But, the data either never gets written or never gets read. I'm not sure which one. My serializeData method is called in onDestroy and the deserializeData is called from onCreate. Here's my code for writing and reading the data:

public void serializeData(String filename, ArrayList<String>arrayList) {
    FileOutputStream fos;
    try {
        fos = openFileOutput(filename, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(arrayList); 
        oos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
}

@SuppressWarnings("unchecked")
private void deserializeData(String filename, ArrayList<String>arrayList){
    try{
        FileInputStream fis = openFileInput(filename);
        ObjectInputStream ois = new ObjectInputStream(fis);
        arrayList = (ArrayList<String>)ois.readObject();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }catch(ClassNotFoundException e){
        e.printStackTrace();
    }
}

任何帮助将大大AP preciated!在此先感谢!

Any help would be greatly appreciated! Thanks in advance!

推荐答案

让我告诉你一件事:从来不使用的onDestroy()方法来保存数据。使用的onPause()或的onStop()代替。你不应该在的onDestroy()方法计数保存数据或致电某些功能。

Let me tell you one thing: never use the onDestroy() method to save your data. Use onPause() or onStop() instead. You should never count on the onDestroy() method to save data or call some functions.

使用的onDestroy关闭连接,并使用资源等,完成。如果您想了解更多关于这个你应该看看

Use onDestroy to close connections and finish using resources and the like. If you want to read more about this you should take a look here.

除此之外,您的code似乎罚款。只需添加一件事:把一个oos.flush()略高于oos.close()

Other than that your code seems fine. Just add one more thing: put a oos.flush() just above oos.close().

和不要忘记关闭的ObjectInputStream对象。

And dont forget to close the objectInputStream object.

感谢。

这篇关于序列化一个ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆