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.
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
Save the items in a parent activity or static utility class.
Otherwise, you can use the manifest to tell the app to not destroy the activity on screen resizes. Check out this article: http://developer.android.com/guide/topics/resources/runtime-changes.html
Actually there is a very nice article on the Android Developer site which covers this topic.
Some devices, like the T-Mobile G1, can change their hardware configuration at runtime. For instance, when you open the keyboard, the screen change from the portrait orientation to the landscape orientation.
To make Android app development easier, the Android system automatically handles configuration change events and restarts the current activity with the new configuration.
[...]
While this behavior is really powerful, since your application adapts automatically to the device's configuration at runtime, it is sometimes confusing for new Android developers, who wonder why their activity is destroyed and recreated.
Facing this "issue," some developers choose to handle configuration changes themselves which is, in general, a short-term solution that will only complicate their lives later.
[...]
The full article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With