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

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

问题描述

我正在尝试编写一个 Android 游戏,并且即使用户想要返回主菜单或活动被系统终止,我也希望能够暂停游戏.onSaveInstanceState 似乎并没有给我很多关于何时可以读取包的控制权,而且据我所知,包只在短时间内有效.所以我想序列化我拥有的一些 ArrayList,然后读回它们.我没有收到任何编译错误,程序也没有崩溃.但是,数据要么永远不会被写入,要么永远不会被读取.我不确定是哪一个.我的 serializeData 方法是在 onDestroy 中调用的,而 deserializeData 是在 onCreate 中调用的.这是我编写和读取数据的代码:

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();
    }
}

任何帮助将不胜感激!提前致谢!

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.

除此之外,您的代码看起来还不错.再添加一件事:在 oos.close() 上方放置一个 oos.flush().

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

并且不要忘记关闭 objectInputStream 对象.

And don't forget to close the objectInputStream object.

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

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