开发者

Serializing an ArrayList

I'm trying to write an Android game and I would like to be able to pause th开发者_如何学Pythone 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!


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.

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.

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

And don't forget to close the objectInputStream object.


I cannot see an obvious problem with that code.

I'd try adding some code after closing the ObjectOutputStream and before opening the ObjectInputStream to print out the absolute name and size of the file.


While serializing you can write to ByteArrayOutputStream and then decode the bytes into string using platform's default character set. Store this string into SharedPreferences. While deserializing, just get the bytes from string and create a ByteArrayInputStream using this and feed it to ObjectInputStream.
Are you sure your activity is being killed? It might be the case that your activity is oscillating between onPasue/onResume.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜