Search code examples
androidandroid-activityactivity-lifecycleandroid-database

Best Practice - Saving Activity data to android database


I currently store my app data for an Activity in a Parcelable object. On orientation change, I save it and load it by using onSaveInstanceState and onRestoreInstanceState.

I want to save the data to the database when the user exits the activity.
And, I want to minimize the database calls. So,

Where should I write the code to save the data to database? Is it onPause(), onResume(), onStop() or onDestroy()?


Solution

  • I currently store my app data for an Activity in a Parcelable object

    Since the rest of your question is about database I/O, please note that Parcelable has nothing to do with database I/O.

    I want to save the data to the database when the user exits the activity.

    I would recommend that you save the data when the data changes, rather than wait and risk losing that data (e.g., app crashes).

    Is it onPause(), onResume(), onStop() or onDestroy()?

    It is not onResume(). That lifecycle method is called as part of activity coming onto the screen, not when the activity is leaving.

    It is not onDestroy(), as there is no guarantee that onDestroy() will be called.

    Either of the other two are reasonable. The primary difference is visibility:

    • If an activity takes over the foreground, but that activity is themed like a dialog or otherwise allows your activity to peek through, you are only paused

    • If an activity takes over the foreground, and your activity is no longer visible, you are paused and then stopped