Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

asynchronous - Android AsyncTask in external class

I've been working on an app and I've managed to get the AsyncTask to work fine when it's in an inner class.

Now, I am refactoring the code so that the AsyncTask is in a separate class of its own, but I 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.


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, maybe I'm missing something but that didn't work for me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of passing 2 parameters pass only one like this:

public class Test101 extends Activity {
    private Button btnLogin;
    private LoginTask mLoginTask;

    mLoginTask=new LoginTask(this);
    mLoginTask.execute(); 
    //Instead of sending null put the 1st parameter of the AsyncTask as Void

AsyncTask Code:

  Activity mParentActivity;

public LoginTask(Activity act){
    this = act;
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...