Serialization ArrayList

I am trying to write an Android game, and I would like it to pause the game, even if the user wants to return to the main menu or the activity will be destroyed by the system. onSaveInstanceState doesn't seem to give me much control over when I can read the package back, plus from what I can tell, the package is only good for short periods of time. So I want to serialize a few ArrayLists that I have, and then read them back. I have no compilation errors and program crashes. But the data is either never written or never read. I'm not sure which one. My serializeData method is being called on onDestroy, and deserializeData is being called from onCreate. Here is my code for writing and reading 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!

+4
source share
3 answers

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

Use onDestroy to close connections and end resource usage, etc. If you want to know more about this, you should look here.

Also, your code seems great. Just add one more thing: put oos.flush () just above oos.close ().

And don't forget to close the objectInputStream object.

Thanks.

+4
source

I do not see an obvious problem with this code.

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

0
source

When serializing, you can write to ByteArrayOutputStream and then decode the bytes into a string using the default character set for the platform. Save this line in SharedPreferences. During deserialization, you can simply get the bytes from the string and create a ByteArrayInputStream using this and pass it to ObjectInputStream.
Are you sure your activity is killed? Perhaps your activity fluctuates between onPasue / onResume.

0
source

Source: https://habr.com/ru/post/1342239/


All Articles