Imagine a scenario where you are starting an AsyncTask in the onCreate of an Activity and using it to update a progressBar. When you rotate the device, the Activity is recreated and onCreate is called again, hence the AsyncTask begins again. Meanwhile, when the previous AsyncTask finishes, its result is lost as the Activity it was associated with doesn’t exist anymore. To avoid such a situation, we should use a Fragment.
1) Create a CallBack Interface for passing data from Fragment to Activity.
2) Create a new Activity and find the ProgressBar. Also implement CallBack interface and override the updateProgress method to update the ProgressBar.
3) Create a Fragment without a UI. Create an instance of CallBack interface and assign it the value of Activity received in the Fragment’s onAttach. This way, your Fragment keeps track of the most recent Activity object.
Also override the onCreate method and write setRetainInstance(true). This line is particularly important as it allows Fragment’s state will be retained across the configuration change. For a better understanding of setRetainInstance, go through this link – http://stackoverflow.com/questions/11182180/understanding-fragments-setretaininstanceboolean.
4) Create an AsyncTask in your Fragment’s onCreate and execute it. Do your background processing inside doInBackground method and also override the onProgressUpdate method to publish the progress update to your activity using the CallBack instance. For the sake of simplicity and showing progress updates smoothly, I am hitting the same URL five time and publishing progress in between successive calls.
5) Also, don’t forget to put callBacker to null inside onDetach of the Fragment.
6) Now, come back to your MainActivity and create an instance of this Fragment. Hook it up with a TAG so that after configuration change, inside your Activity’s onCreate, you can check if the Fragment is still active using this TAG and take proper action.
For the first time, when we try to find a Frafment using the TAG, it will return null since no Fragment is active. In that case we add a new Fragment which in turn starts an AsyncTask. After device rotation, onCreate will be called again, but this time due to setRetainInstance being set to true, it will find the Fragment to be non-empty and not do anything.
Although onAttach of Fragment will be called and it will receive an instance of the newly created Activity. Hence it will send progress updates to the correct Activity.
Download code from here :
https://www.dropbox.com/sh/4aurs87w507g3g0/AACtU3mLLKbHbbBL1PZAqcR1a?dl=0