Restoring complex objects at restart of an activity

In an android app an activity is created and then destroyed, for example when the user open another activity or when the user presses the back button, later the user opens again the same activity that is is recreated using the data saved before the earlier destruction of the activity.
The data are saved in an object Bundle in the onSaveInstanceState method and restored in the onRestoreInstanceState method (see Recreating an Activity).
The Bundle class provides several setter and getter methods to save and restore data such as getInt and setInt for the integers and similar methods for other types of primitives, strings and one dimensional array.
In this post I write some examples to save and restore more complex objects such as the following CustomObject:


Passing an object from an Activity to another

The method startActivity(Intent intent) of the class Activity allows you to call a second activity specified using the argument Intent.
You can associate primitive data or primitive data array to the argument Intent and then the second Activity can access them, you can also pass objects of type String using methods of the class Bundle like put*().
In this post I show an example to pass a more complex object between an Activity and another.


Getting the Context inside a Fragment

It is very easy to get the Context inside an Activity:

  • with the getApplicationContext() method
  • using only “this” because the Activity class extends the Context class

But you can’t use any of these two methods inside a Fragment and you have to replace them respectively with:

  • getActivity().getApplicationContext()
  • getActivity()

I often do this replacement when I use code written for an Activity, but that I must use in a Fragment.