Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Lifecycle and saving an Instance State questions

So within my application is a form for creating a new user, with relevant details and information about the user. There's no problems there, it's just what happens when the user leaves the activity without pressing the confirm button.

Here's what I want to do:

  1. If the user presses the back button, attempt to save all the data to the database and inform the user.
  2. If the activity is interrupted (ie by a phone call), save all the data into a temporary location so when the activity is at the top of the stack again, nothing appears to have changed (but the data still hasn't yet been saved to the database).
  3. If the activity gets killed for more resources when in the background, do the same as point 2 above (ie when the activity is started again, it appears that nothing has changed).
  4. If the whole application is started again (by clicking on the icon again) and there is temporary data stored from either points 2 or 3 above, navigate to the "create user" activity and display data as if nothings changed.

Here's how I'm currently trying to do it:

  • Use onDestroy() and isFinishing() functions to find when the activity is being killed, to cover point 1 above (to then try and save all data).
  • Save all data with onSaveInstanceState into a bundle (to cover point 2 above)
  • Does the bundle created with onSaveInstanceState survive the activity being killed for more resources, so when its recreated the previous state can be retrieved (as in point 3 above)?
  • No idea how to implement point 4.

Any help would be massively appreciated.

Cheers!

like image 907
The Salt Avatar asked Apr 20 '10 16:04

The Salt


1 Answers

I'm short on time so can't give a full detailed answer, but in brief, here are my suggestions.

  • Instead of using onDestroy(), use onPause(). That's guaranteed to get called; according to the official documentation on Lifecycles, only onPause() is guaranteed. onStop and onDestroy are not.
  • onSaveInstanceState and onPause are similar. Both get called when the app leaves the foreground (i.e. it enters the potential danger zone for being killed), but the difference with oSIS is the temporary bundle it provides. onPause doesn't provide any data storage mechanism, but if you're using a database than you already have one. According to the documentation, there isn't a guaranteed order to which one gets called first.
  • Point 3) That's exactly what oSIS is meant for
  • Point 4) You could make a 'temporary row' in your database, i.e. save temporary data to row 1, but whenever a save is properly made, row 1 gets blanked. Then in your onCreate(), check whether row 1 has real data or is empty. (If your columns can't be empty, then use pre-determined placeholder values that wouldn't ever appear as part of normal use.)
like image 90
Steve Haley Avatar answered Nov 15 '22 07:11

Steve Haley