If I save persistent data in onPause(), how can I cancel the modifications later?
In android, I'm trying to create an simple activity allowing me to modify a record from a database. In the onCreate method I load the record data from the database in different views on the activity allowing the user to modify the information. If the user click on Ok, I save back the data to the database and call finish()
. If the user click on Cancel, I don't save the data and call finish to return to the previous activity.
Now, I just learnt that it is recommended in the android documentation to commit the unsaved changes to persistent data in the onPause()
event.
I see a couple of problems about this. First, onPause()
might be called while the data in the field doesn't form a valid record, so it certainly can't be saved in the database. Second, even if the data was valid, if I save what should I do if the user later click on the cancel button because he doesn't want his changes saved. I would no longer have access to the original record. And finaly, if the user click on Cancel and I call finish() to go back to the previous activity onPause() will be called and the data saved开发者_开发技巧 while it shouldn't.
In my opinion it would make more sense to save all the data in the Bundle offered by the onSaveInstanceState() method and reaload it from the onCreate() method if my activity ever gets killed.
How should I handle this?
This is exactly a case for onSaveInstanceState(). If your app isn't killed by the system, your data will still be there when the activity is displayed again and the onResume method is called, so no need to save anything in that case. If you app is killed, onSaveInstanceState should do the trick. I wouldn't consider what you describe like unsaved changes, because, as you say so yourself, it could be in an invalid state. It's just a temporary state.
精彩评论