Saving some data on orientation change in Android

Michell Bak picture Michell Bak · Aug 23, 2011 · Viewed 9.8k times · Source

As far as I've understood, your Android activity will be recreated for the new orientation on any orientation changes.

Is there a way to store / save some of the data from the original orientation upon the orientation change?

I'd like to store some Bitmaps, so I don't have to load it again on the orientation change.

Answer

Pedro Loureiro picture Pedro Loureiro · Aug 23, 2011

Using static variables/classes is a bad approach in terms of maintainability and debugging.


I have been using Activity.onRetainNonConfigurationInstance but I found out just now that this is deprecated (probably since honeycomb or later). Activity.onRetainNonConfigurationInstance

Using this method, just call Activity.getLastNonConfigurationInstance to retrieve the same object you returned in the onRetainNonConfigurationInstance. Be sure to check for null and cast to the right class (you can return/get any class). Activity.getLastNonConfigurationInstance

A sample usage in pseudo-code would be:

onRetainNonConfigurationInstance:
    return "I need to remember this next time";

onCreate:
    ...
    String messageToShow = null;
    Object data = getLastNonConfigurationInstance();
    if(data != null)
        messageToShow = (String)data;
    else
        messageToShow = "Nothing to show";

So, if you are targetting up to 2.x.x you can use that method. Otherwise, google recommends you to use Fragment.setRetainInstance. This is backwards compatible via the compability package.

Fragment.setRetainInstance