0

I have a asynctask that I cancel when the view is destoried via onDestoryView(). This problem is I do "downloader.cancel(true);" and it wont cancel. In fact, it will return false. Currently, it references the ListAdapter to add items to it. However when I turn the screen to landscape, the ListAdapter is null during the onPostExecute. I cannot figure out when the ListAdapter becomes null. I have tried both onDestory and onDestoryView to cancel the asynctask before the ListAdapter becomes null but it never works. This is inside of a ListFragment btw.

For the time being, I just check if the adapter is null in the asynctask but this really grinds my gears. I would rather just cancel the task before the ListAdapter is null.

Does anyone know when the ListAdapter is null for a ListFragment during screen rotations?

David Stocking
  • 1,200
  • 15
  • 26
  • here read on how to cancel AsyncTask http://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask – Sergey Benner Feb 02 '12 at 21:08

2 Answers2

1

Cancelling an AsyncTask does not kill the Thread. You will see in the docs for Thread that methods like stop and destroy are unimplemented. So once the doInBackground method starts executing, it will run to completion even if the task is cancelled with cancel(true). You will need to code it appropriately.

Lawrence D'Oliveiro
  • 2,768
  • 1
  • 15
  • 13
  • But I thought that the AsyncTask ran synchronously once inside of the doInBackground? If so then shouldnt it be true that A) we hit doInBackground before ListAdapter == null or B) we cancel the AsyncTask before it does doInBackground and it instead does onCancelled? I guess I don't understand what AsyncTask is doing. – David Stocking Feb 03 '12 at 01:25
0

When the screen orientation is changed the default behavior is destroy the Activity and recreate it. So the methods OnDestroy, and OnCreate will be called. You can cancel this behavior adding this line in the activity that of your your Manifest:

android:configChanges="keyboardHidden|orientation"

Like that:

    <activity
        android:name=".YourActivity"
        android:label="@string/app_name"
        android:configChanges="keyboardHidden|orientation" >

You also needs to add the method onConfigurationChanged in your activity class.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig); // tem que ter

    reconfiguraInterface();
}

After that OnDestroy and OnCreate will not be called when orientation changes.

Derzu
  • 7,011
  • 3
  • 57
  • 60