I am new into Android development and I am making a Flash Card like application.
I am writing the Card object into a file using ObjectOutputStream
and reading it using ObjectInputStream
.
I was thinking what will happen when the application is trying to write a Card into a file by updating it in the temporary physical memory and the user closes the application when the writing process is taking place.
The file will be in an inconsistent state and will lead to unexpected logical errors in the application.
ObjectInputStream ois = new ObjectInputStream(openFileInput(FILE_NAME));
Card c = (Card) ois.readObject();
c.foo = foo + 1;
ois.close();
ObjectOutputStream oos = new ObjectOutputStream(openFileOutput(FILE_NAME, MODE_PRIVATE));
// At this point the file will be truncated as the file is opened in write mode
// User closes the application here at this point
// Card has been updated but not stored into the file
oos.writeObject(c);
oos.close();
Can we make this group of code atomic so that even if the user closes the application in between, all the changes will be roll backed?
Or can we disallow the user to stop the application at this point?
By closing the application, I mean killing the app but I would like to know what happens in other cases too like pressing the back button, pressing the home button, etc.