Free Android app covering all aspects of addiction, including prevention and treatment

Fragments, configuration changes and retaining objects

  • Written by  Clive

Using fragments to rebuild your activities

Android configuration change and ragments icon

An activity is destroyed and recreated when a device’s configuration changes.

Usually the activity’s lifecycle takes care of saving and restoring its state. Sometimes you may need to restore lots of data. This could take some time resulting in a bad user experience.

Here’s where you can use fragments to retain an instance of your data. You can then get the data out of the fragment and rebuild your activity, super fast!

Be careful not to save objects that are tied to the activity; such as drawables, adapters, views or any other objects associated with a context. They’ll cause memory leaks – the object keeps a reference to the context (the activity for example), so it will remain in memory, leaving less for your app to use.

Have a look how easy it is to use a fragment to save an Object during a configuration change!

Our tutorial app

A brief summary of our tutorial app

We have an activity, a fragment and a data object.

The activity displays the data object (an image and some text). We save the data in the fragment - it keeps a reference to it.  The fragment is marked so that it’s not destroyed along with the activity.

Android configuration change and fragments Diagram

Here’s a diagrammatic representation of our tutorial app. Our activity displays some data. The fragment retains a reference to that data. When the activity is destroyed, the fragment is not. We can then retrieve the data from the fragment and use it to rebuild the activity

Android configuration change and fragments tutorial app screenshot

The default screen: Pressing the button simulates downloading a bitmap and some text data which is then displayed

The activity is destroyed and then recreated each time the device’s configuration changes.

The fragment isn’t destroyed so we can get the retained data object out of the fragment and display it in the activity.

Android configuration change and fragments tutorial app screenshot

The bitmap and text data has been downloaded and displayed

Android configuration change and fragments tutorial app screenshot

We change the screen orientation and the activity is destroyed and recreated. The downloaded data is retained by the fragment. We get the data out of the fragment, rebuild the activity and display the data

The Data Object

Our data object class contains the bitmap, name, email and phone fields as well as their getter and setter methods.

The Fragment

A quick summary of the fragment

Our fragment won’t be destroyed when the activity is. So we use it to save, or keep a reference to our data object. We can then get the data object out of the fragment when want to rebuild the activity.

We’re using the Support library for our fragment so that you can use fragments on devices running Android 1.6 (API Level 4) and up. Make sure that you import the support library class.

Let’s look at the code

Here’s the code for our fragment:

Android configuration change and fragments tutorial fragment

Our worker fragment: It does not have a User Interface and is only used to keep a reference to our data object

Note the following:

  • Use the fragment support class
  • The fragment does not have a User Interface
  • MyDataObject – our data object that the fragment will retain a reference to when the activity is destroyed. The activity will get this data object out of the fragment when it’s recreated
  • setRetainInstance – we set this to true to ensure that the fragment is not destroyed along with the activity
  • setData – we set the data to be retained by the fragment. We pass it the data object when we call setData() in the activity
  • getData – we get the retained data object out of the fragment when we call getData() in the activity

The Activity

We’re using the support library so make sure that you import its classes:

Android configuration change and fragments tutorial import support library

Import the support library’s FragmentActivity and FragmentManager classes

A quick summary of the activity

The activity first displays some default text fields and bitmap.

Pressing the button simulates downloading some text and a bitmap which are then displayed.

We put the text and bitmap into a data object and put the data object in the fragment.

The activity is destroyed when the device’s configuration changes but the fragment isn’t. When the activity is recreated, it gets the data object out of the fragment and displays this data.

Let’s look at the code

Here’s the first bit of code:

Android configuration change and fragments tutorial activity

We’re using the support library so we extend the FragmentActivity class to create our activity

Note the following:

  • we’re using the support library so we must extend the FragmentActivity class
  • dataFragment – this is our SavedFragment fragment. We’ll use it to save a reference to our data object
  • newObject – this is our MyDataObject object which we’ll retain in the fragment when the activity is destroyed. We create a new instance of it in the activity’s onCreate() method
  • theName, theEmail, thePhone and theBitmap are data object fields. They are displayed in the activity
  • isDataLoaded – a boolean which we use to confirm that we have “downloaded” new data
  • setDefaultData – our method that assigns default values to our data object fields

Setting the default values

Here’s the code for the setDefaultData() method:

Android configuration change and fragments tutorial activity setDefault values

We use this method to set the default values for the text and bitmap fields

Note the following:

  • we set the default values that will be displayed when the app starts
  • theBitmap – we use the ic_launcher drawable as our default bitmap

Our activity has a number of text views that we use to display the data object’s text fields. There is also an image field that displays the bitmap as well as a button. Pressing the button “downloads” our data.

Downloading our data

Here’s the code that’s executed when the button is clicked:

Android configuration change and fragments tutorial activity buttonClick

Clicking the button downloads the data, displays it and also saves it in the fragment

Note the following:

Here we get the “downloaded” data and put it into our data object. We also display this data and set it to be retained by the fragment when the activity is destroyed.

  • myStringDataArray – a string array that we’ll use to hold the text data that we “download”
  • downloadMyData – simulates downloading the data but actually just assigns values to our data object’s text fields. These are returned as a string array
  • downloadMyBitmap – we simulate downloading a bitmap image. In fact we get the image out of the res/raw folder
  • newObject.set<type> - we call the MyDataObject’s set methods to set the “downloaded” data in the data object
  • setText – we display newly “downloaded” text data in the text fields
  • setImageBitmap – we display the newly “downloaded” bitmap
  • setData – we set the data object containing our newly “downloaded”  data to be retained by the fragment when the activity is destroyed
  • isDataLoaded – we set it to true, indicating that we have new data that should be used when the activity is recreated (else we’ll use the default values)

Check to see if the fragment exists

Next, whenever the activity is created, we check to see if our fragment exists. Here’s the code that does that:

Android configuration change and fragments tutorial activity getSupportFragmentManager()

Check if the fragment exists by looking for its ID tag

Note the following:

  • getSupportFragmentManager - we’re using the support library so we use its version of getFragmentManager() to get an instance of the Fragment Manager
  • findFragmentByTag – when we create the fragment, we give it an identity tag. We now use this tag to look for it
  • dataFragment – our instance of the SavedFragment fragment

We use an if statement to check if it’s the first time we’re creating the activity or if it’s a recreation. Here’s the if statement:

Android configuration change and fragments tutorial activity

We check if we’re creating the activity from scratch or if we’re rebuilding it

Note the following:

We’re creating the activity for the first time
  • savedInstanceState – if this bundle is empty, it means that the activity is being created for the first time
  • dataFragment – we create a new instance of the SavedFragment fragment
  • beginTransaction – starts the process of adding the fragment to the activity
  • add – adds the fragment to the activity state. We pass two parameters:
    • the fragment that we want to add
    • the id tag of the fragment. We’ll use this tag to identify this fragment
We’re recreating the activity

If we’re recreating the activity (the savedInstanceState bundle is not empty), then we first check to see if we “downloaded” new data. If we didn’t then we use the default data.

  • isDataLoaded – if it’s true then we have new data. We need to get this data out of the fragment. We’ll use it to restore the activity’s state
  • getData – we get the data out of the fragment and assign it to our newObject data object
  • we then get the data out of the data object (using the MyDataObject’s getter methods)  and assign it to the various fields
  • setDefaultData – there is no new data so we’re going to use the default data

Display the data

We then display the data.

Destroying the activity

Finally we have the onDestroy() method:

Android configuration change and fragments tutorial activity onDestroy

The activity is about to be destroyed so we save the data object in the fragment

Note the following:

  • onDestroy() is called when the activity is about to be destroyed. The fragment would normally also be destroyed here but by calling setRetainInstance(), we have marked it not to be destroyed
  • setData - we set the data object to be retained by the fragment when the activity is destroyed

I hope that you have found this tutorial helpful.

You may also be interested in this article, Persisting the Activity Instance State and this tutorial, Saving the Activity's Instance State: A tutorial.

Want to convert your Activities to Fragments? Check out this tutorial, Converting Android Activities to Fragments

This tutorial was created using Android Studio. You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.