0

I am new to Android.

I have a UI thread, the user clicks "Login." Once they click login, a thread is created (Android's AsyncTask) that goes to the internet (HTTPPost) and validates the input. There is also a "Progress Bar." Now my question is, how do I go back to the Activity (UI thread?) so I can close and start a new activity.

One naive idea that I came up with was to make the AsyncTask class a subclass of the Activity. This way in the "onPostExecute" method, I can finish the Activity.

Is there a proper way to do this?

sv94
  • 131
  • 2
  • 15

4 Answers4

2

you can pass context of activity in the contructor of asyntask and in onPostExecute you can close that activity by its context and startActivity from there.

public class MyAsyn extends AsyncTask<String, Void, Void>{

public MyAsyn(Context con) {
    context = con;
}

}

and then in onPostExecute do

i = new Intent(context,AnotherActivity.class);
                    context.startActivity(i);
                    ((Activity) context).finish();
Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45
2

call this method in async task

protected void onPostExecute(String result) {

        if(progressDialog!=null&&progressDialog.isShowing()){
            progressDialog.dismiss();
        }


    }
Ketan Ahir
  • 6,678
  • 1
  • 23
  • 45
Shahil Modan
  • 358
  • 1
  • 11
1

Yes you could make Asynctask an inner class of the Activity and use startActivity in onPostExecute.

If its in a spearate .java file then you can pass context to the constructor of asynctask and startActivity

Or you could use interface as a callback to the Activity and start Activity in activity itself. You could also use a Handler.

How do I return a boolean from AsyncTask?

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
1

Call startActivity in the postexecute method of AsyncTask. This will return to the Activity class.

Anjali
  • 206
  • 3
  • 10