title: WeakReference/AsyncTask pattern in android
body: <p>I have a question regarding this simple frequently occurring situation in android . </p>
  
  <p>We have a main activity , we invoke an AsyncTask alongwith the reference of the mainactivity , so that that the AsyncTask can update the views on the MainActivity.</p>
  
  <p>I will break down the event into steps</p>
  
  <ul>
  <li>MainActivity creates an AyncTask , passes its reference to it .</li>
  <li>AysncTask , starts it's work , downloading ten files for example</li>
  <li>The user changed the orientation of the device. This results in an orphan pointer in the AsyncTask </li>
  <li>When the AsyncTask completes , and tries to access the activity to update the status , it crashes ,   because of the null pointer . </li>
  </ul>
  
  <p>The solution for the above is to keep a WeakReference in the AsyncTask as recommended by the book "Pro Android 4" </p>
  
  <pre><code>WeakReference&lt;Activity&gt; weakActivity;
  
  in method onPostExecute
  
  Activity activity = weakActivity.get();
  if (activity != null) {
     // do your stuff with activity here
  }
  </code></pre>
  
  <p>How does this resolve the situation ?</p>
  
  <p>My question it , if my asynctask is downloading ten files , and upon completion of 5 the activity is restarted (because of an orientation change) then would my FileDownloadingTask be invoked once again ?. </p>
  
  <p>What would happen to the previous AsyncTask that was initially invoked ? </p>
  
  <p>Thank you  , and I apologize for the length of the question .  </p>