6

Is there any possibility of defining a single instance of AsyncTask, rather than defining in every class ?

Or it is designed to be defined separately for each activity ?

I have 4-5 activities, each with different url to request, and for url's response, I have defined a separate class with methods to parse and populate objects as per request made.

EDIT: I made a mistake above. Actually, should I define a single class extending from AsyncTask and or define a private class inside each Activity where required ?

My apologies, I am a bit confused.

Thanks.

user3141985
  • 1,395
  • 4
  • 17
  • 36
  • Why you would like to create it in every task? Just define one class, execute it and override the onPostExecute – A.S. Mar 25 '14 at 08:25
  • put only that code in asyntask that si execute on network mean execute request in asyntask. and then handle response on your behalf according to what you get. – Waqar Ahmed Mar 25 '14 at 08:26
  • pass the context of the activity and use that from different activity by creating a simple async task class – Developer Mar 25 '14 at 08:26
  • what do you think about fragment for doing async operations? you can use it from any activity and it will be reusable too. reference: [this](http://stackoverflow.com/questions/15271271/android-callback-asynctask-to-fragmentnot-activity) – Mehul Joisar Mar 25 '14 at 08:29
  • @A.S. I want to avoid multiple definitions. – user3141985 Mar 25 '14 at 08:31

4 Answers4

7

No, because an AsyncTask can be executed only once (an exception will be thrown if a second execution is attempted). So you have to create a new instance of the AsyncTask every time you want to execute it.

makovkastar
  • 5,000
  • 2
  • 30
  • 50
  • I am not asking about the instance, I am asking about defining. At present what I have seen in examples and done is defined a private class that extends from AsyncTask. – user3141985 Mar 25 '14 at 08:33
  • @user3141985 usually it's defined as an inner class to have an access to an enclosing context, but for sure you can have a separate top-level class that extends AsyncTask and pass context as an argument to a constructor. But be aware that during AsyncTask execution the context that it holds can easily become invalid (activity can be destroyed). – makovkastar Mar 25 '14 at 08:38
  • Though this is mentioned in https://developer.android.com/reference/android/os/AsyncTask.html, under the title of Threading rules it was easier to find it from here. Thanks. – Pulathisi Bandara Nov 04 '17 at 10:20
5

Hope this helps you:

public class MyAsynctask extends AsyncTask<String, Integer, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        int i = 0;

        for (int x = 0; x < 500; x++) {
            i++;
        }
        return i;
    }

    @Override
    protected void onPostExecute(Integer result) {

        super.onPostExecute(result);
    }

}

Activity wich uses the Asynctask:

public class MyAsyncUser extends Activity{

    int result;
    TextView view;
    public void onCreate(android.os.Bundle savedInstanceState) {

        view = new TextView(this);

        new MyAsynctask(){
            protected void onPostExecute(Integer result) {
                view.setText("" + result);
            }       
        }.execute("what to do");
    }
}

So you can define a Asynctask class and use it and make something with your result in deífferent places.

A.S.
  • 4,574
  • 3
  • 26
  • 43
0

My dear friend, it can be done but not recommended in your case. If you still want to implement it, then create a BaseActivity class to implement the AsyncTask and override url function. But One Thing to remember:, Don't forget to close, pause the asynctask instance during switching of activities.

Attiq ur Rehman
  • 475
  • 1
  • 6
  • 21
  • What is the correct scenario of defining AsyncTask, should it be defined for each activity where required, or a single definition and execute from there. To avoid multiple executions at the same time, I can set a flag that can be checked if the AsyncTask is in execution. – user3141985 Mar 25 '14 at 08:38
  • No dear, setting flag is a bed choice. Just implement aysnctask in your BaseActivity class and implement it in your ActivityA, ActivityB with singleInstance mode. There will be an instance of asynctask in each class so, every execution will take place in parallel. So, there will be no problem of multiple executions – Attiq ur Rehman Mar 25 '14 at 08:42
  • How is flag a bad choice to avoid multiple execution of AsyncTask while an instance is already in execution ? – user3141985 Mar 25 '14 at 08:45
  • Bro, there will be no need of flags because each activity is going to have its own instance of asynctask function. – Attiq ur Rehman Mar 25 '14 at 08:46
0
Is there any possibility of defining a single instance of AsyncTask, rather than defining in every class ?

If your only concern is to define it in separate file, then YES , that is possible and valid.

Cons:

It may leak the activity context if you try to show progress dialog over there.

It may try to give callback to the activity which does not exist anymore because user might have moved further.

EDIT :

If you are beginner in android development, for the sake of simplicity I would suggest to define a private class inside each Activity where required.

If you are experienced then try to use Fragment for async operations as mentioned here

Community
  • 1
  • 1
Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57