views:

764

answers:

3

I've been working on an app and I've managed to get the AsyncTask to work fine when it's an inner class, am refactoring the code so that the AsyncTask is a separate class on its own but am wondering how do I kill the ProgressDialog and start a new Activity once the task is completed successfully? I've tried starting a new Activity in the onPostExecute(..) method but I know that won't work

A: 

pass the Activity as a constructor parameter to your AsyncTask and keep it in a field. this is effectively what being an inner class was getting you (only the compiler would write the code for you).

Elliott Hughes
I modified my AsyncTask constructor to:public LoginTask(Context context,Activity ax){ super(); this.ctx=context; this.mActivity=ax; }and then in onPostExecute() i tried start a new activity:mActivity.startActivity(i);I got a null pointer exception
jwesonga
+3  A: 

All one needs to start a new Activity is the context object that you pass in the constructor of the AsyncTask:

    private Context ctx;
        private ProgressDialog pDialog;
        private String r="";



        public LoginTask(Context context){
            super();
            this.ctx=context;

        }

@Override
    protected void onPostExecute(String result) {


            Log.i("LOGGER", "Done...");
            pDialog.dismiss();
            Intent i=new Intent(ctx,SillyActivity.class);
            ctx.startActivity(i);


    }

If you pass the activity within the constructor in the AsyncTask and try to call startActivity(Intent intent) you will always get a null pointer exception..

jwesonga
A: 

Passing my UI thread activity as an argument in the constructor for the AsyncTask did not seem to work:

//In UI Thread I had
public class Test101 extends Activity {
    private Button btnLogin;
    private LoginTask mLoginTask;
    private Context context=this;
        private Test101 mTest101;

mLoginTask=new LoginTask(context,mTest101);
mLoginTask.execute(null);

//In the AsyncTask I had

Activity mParentActivity;

public LoginTask(Context context,Activity act){
this.ctx=context;
this.mParentActivity=act;
}

onPostExecute(..){
  mParentActivity.callSomeMethod();
}

I kept getting a NullPointerException, may be I'm missing something but that didn't work for me.

jwesonga