Android interface Serializable is not sufficient to save your objects to the file, it only creates streams.
This is a complete code with error handling and handling closes of streams. Add it to your class that you want to be able to serialize and deserialize.
In my case the class name is CreateResumeForm. You should change it to your own class name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Constant with a file name public static String fileName = "createResumeForm.ser"; // Serializes an object and saves it to a file public void saveToFile(Context context) { try { FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(this); objectOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } // Creates an object by reading it from a file public static CreateResumeForm readFromFile(Context context) { CreateResumeForm createResumeForm = null; try { FileInputStream fileInputStream = context.openFileInput(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); createResumeForm = (CreateResumeForm) objectInputStream.readObject(); objectInputStream.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return createResumeForm; } |
Use it like this in your Activity:
1 |
form = CreateResumeForm.readFromFile(this); |