Kris B
Kris B

Reputation: 3578

Fragment switching with AsyncTask

My apps uses fragments to show a ListView in portrait mode or the ListView and "details" view, side-by-side, in landscape mode. I also have a menu item in the ActionBar that kicks off an AsyncTask. The problem is, if the user rotates their display from portrait to landscape (or vice versa) while the AsyncTask is running, the AsyncTask is killed. To fix the AsyncTask from stopping, I added the configChanges attribute to the AndroidManifest:

    <activity android:name="ListingFragment" android:configChanges="keyboardHidden|orientation" />

However, adding that attribute then prevents the fragments from automatically switching to the landscape/portrait view. Is there any way to have the fragments automatically switch their views without killing the AsyncTask?

Upvotes: 0

Views: 1179

Answers (1)

dmon
dmon

Reputation: 30168

You need to save the instance of your asynctask before the activity gets killed. You can use onRetainCustomNonConfigurationInstance() to save it. Then in your oncreate you can retrieve it using getLastCustomNonConfigurationInstance(). Then in your onCreate you can "attach" your activity to the asynctask again.

Upvotes: 1

Related Questions