Skip to content Skip to sidebar Skip to footer

The Asynctask Fails When I Rotate The Device To Landscape

I have an Activity in which I have a ProgressBar,an ImageView and a TextView,I update all three from an AsyncTask.All three get updated when the screen is completely in one orienta

Solution 1:

When orientation changes your activity gets is destroyed and recreated. Fragments are hosted by an activity.

By default, Fragments are destroyed and recreated along with their parent Activitys when a configuration change occurs. Calling Fragments setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated.

publicvoidsetRetainInstance (boolean retain)

Added in API level 11
Control whether a fragment instance is retained across Activity re-creation (such asfrom a configuration change). This can only be used with fragments notin the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:

onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
onCreate(Bundle) will not be called since the fragment isnot being re-created.
onAttach(Activity) andonActivityCreated(Bundle) will still be called.

You can check this blog for a workaround suggested . Uses interface as callback to the activity.

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

and the source code for the same is available at

https://github.com/alexjlockwood/worker-fragments

Quoting from the blog

Flow of Events

When the MainActivity starts up for the first time, it instantiates and adds the TaskFragment to the Activity's state. The TaskFragment creates and executes an AsyncTask and proxies progress updates and results back to the MainActivity via the TaskCallbacks interface. When a configuration change occurs, the MainActivity goes through its normal lifecycle events, and once created the new Activity instance is passed to the onAttach(Activity) method, thus ensuring that the TaskFragment will always hold a reference to the currently displayed Activity instance even after the configuration change. The resulting design is both simple and reliable; the application framework will handle re-assigning Activity instances as they are torn down and recreated, and the TaskFragment and its AsyncTask never need to worry about the unpredictable occurrence of a configuration change.

Post a Comment for "The Asynctask Fails When I Rotate The Device To Landscape"