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

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!