midhunhk
midhunhk

Reputation: 5554

Storing complex computed data between orientation change

In the onCreate() of my MainActivity, my app does an intensive operation to generate some data set (runs in a separate thread, but takes some 2 - 3 seconds to complete normally). Now my problem is that, when orientation changes, the app again does this complex computation again.

Since I haven't done anything like this before, I was wondering if there is a way around this. My first thought was to store the computed data in a static variable, so that the data is persisted between different instances of MainActivity. I am guessing this is not the best approach.

My data set consists of a Map and an ArrayList and not a simple data type, if it helps. I have looked at the onSaveInstanceState(), but it only provides to store values like int, String, etc.

Upvotes: 1

Views: 513

Answers (1)

Shobhit Puri
Shobhit Puri

Reputation: 26017

In addition to what @Raghunandan suggested you can read the official docs on Recreating an Activity . It says:

Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout.

It also introduces the concept of onSaveInstanceState()(To save additional data about the activity state, you must override this method) and onRestoreInstanceState() method (The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle)).

You can also see the sample implementation of these methods here Saving Android Activity state using Save Instance State thread, which will help you to save and restore the state.

Update

You may also try using:

<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

The docs for android:configChanges say;

It lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Source: How to save state during orientation change in Android if the state is made of my classes? Hope this helps.

Upvotes: 1

Related Questions