序列化ArrayList中的Andr​​oid不工作 [英] Serializing ArrayList android not working

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

问题描述

更新:后位的测试,我确定自己被心不是创建的文件,至少根据file.exists反正检查。任何想法?

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?

你好,我想在我的应用程序退出序列化一个ArrayList和读回的续时。它似乎没有要创建该文件。

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.

下面是我的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) {
                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();
        }
    }




}

任何想法?我为MyObject类实现序列化。

Any ideas? My MyObject class implements serializable.

推荐答案

明白了通过更改的FileInputStream FILESTREAM =新的FileInputStream(文件名)的FileInputStream FILESTREAM = openFileInput(文件名)。

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

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