Android: Handler for AsyncTask
<p>I use AsyncTask in combination with a ProgressDialog.
See my code, I have a problem in onPostExecute.
If the task is running for the first time it get a Null Poiter Exception for progressDialog in handleMessage but calling dismiss() direct would work.
When I turn the phone before onPostExecute is reached, progressDialog.dismiss() does not work. why does the handler not always work?</p>

<pre><code>public class UpdateTask extends AsyncTask&lt;Void, Void, Void&gt; {
    private ProgressDialog progressDialog;
    private Handler handler;

public UpdateTask(Act activity) {

        progressDialog = ProgressDialog.show(Activity.this, "Wait",
                "Wait");
        progressDialog.dismiss();

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                //run on UI Thread
                switch( msg.what ){
                    case MSG:                       
                        progressDialog.show();
                        break;
                    case DETACH:
                        progressDialog.dismiss();
                        break;  
                }
            }
        }; 

    }


    void detach() {
          activity=null;
                  //problematic
          //progressDialog.dismiss();
          //handler.sendEmptyMessage(DETACH);
        }




    @Override
    protected Void doInBackground(Void... params) {
        handler.sendEmptyMessage(MSG);;
        return null;
    }

    protected void onPostExecute(Void result)    {  
        if (activity==null) {
            Log.w("RotationAsync", "onPostExecute() skipped -- no activity");
          }
          else {
              //problematic
              //                  progressDialog.dismiss();
              handler.sendEmptyMessage(MSG);
                progressDialog = null;
          }
    }

};
</code></pre>
