I have an app which has a main activity that calls other activities on a button press.
The main activity hosts a class which contains a lot of data and is parcelable. the data is the backbone for the application and I need to save it across orientation changes. In order to achieve this it use onSaveInstanceState and put the parcelable object in the bundle.
However, I have noticed that onSaveInstanceState is called everytime i press a button and start one of the new activities as well as on orientation changes. This is slightly slowing down the transition to the other screens.
Is there a good way to only store this information when I know for definite that the activity will be destroyed rather than every time I navigate away from the Activity periodically. I understand that the minute I navigate away from the main activity there is a chance that it may get destroyed.
Thanks,
M<
For primitive values, you should use
onSaveInstanceState. For restoring you can useonRestoreInstanceStateor you can some code inonCreatelike this:Now for restoring big objects like
Bitmapetc if they are not expensive to create and doesn’t make your UI sluggish, create them again on restore. If you do not want to that then useonRetainNonConfigurationInstanceand code will look like this:WARNING: This api is deprecate, you might use it on old platforms. I put it here for illustration purpose. The new way to do this is more involving.
Here is detailed ref:
getLastNonConfigurationInstance
onRetainNonConfigurationInstance
Recommended soln for new api levels 11 and above:
“Use the new Fragment API setRetainInstance(boolean) instead; this is also available on older platforms through the Android compatibility package.” snippet from the doc when you click on the links above.
So, you will create your bitmaps inside the fragment and call
setRetainInstanceon fragment so that fragment and its content (in your case bitmap) will be retained accross config change.Ref:
setRetainInstance