0

I have a number of AsyncTask set up as individual classes. I reuse them throughout my app. I wonder, in places where the same AsyncTask may be needed more than one is it possible to use one instance of that custom AsyncTask class multiple times? This is really a cosmetic problem since it bothers me having redundant sections of code, especially when an AsyncTask uses a callback to communicate with it's starting activity.

I've tried to do it this way -

MyTask task = new MyTask(new someCallBackListener){

    @Override
    public void taskDone(boolean youDone){

    }
});

And then in my activity just calling

task.execute(params);

This seems to work the first time, but I cannot execute it more than once. Do I really just need to initialize a new task each time I want to use it?

Rarw
  • 7,645
  • 3
  • 28
  • 46

2 Answers2

2

An asynctask can be executed only once as per the android documentation here(section Threading rules)which says

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

So its not possible to reuse an AsyncTask instance. Further this SO link would help you!

Community
  • 1
  • 1
rahulserver
  • 10,411
  • 24
  • 90
  • 164
1

While you can't use twice the same instance I think you could reuse the callback implementation by creating the instance this way

new MyTask(this).execute(params);

and implementing the callback in the Activity or the Fragment like this

public class SomeActivity extends Activity implements MyTask.someCallBackListener {

    //All the Activity code

    public void taskDone(boolean youDone) {

    }
}

This way, you can create multiple instances of your AsyncTask without those redundant sections of code that bother you.

Jofre Mateu
  • 2,390
  • 15
  • 26
  • Not a bad idea. I'm going to look into that. – Rarw Jan 21 '15 at 17:04
  • I have done this and it works... but now i have a button in the same activity and I tried to create another instance... but even if i reused teh same one... this still happens... in your example taskDone, what if you wanted a specific instruction to happen on the first use but a different set on the 2nd? So for ex: first time I need it to save the value requested... the 2nd time I need it to save a file. I have the same setup, an interface using a method that I use in teh activity, but its still the same method, i need a different one called back. Is there a way to achieve that? – carinlynchin Feb 01 '17 at 18:03
  • You could have a counter or a boolean in the callback, and use it to know what task you have to perform with a switch or a if/else structure – Jofre Mateu Feb 02 '17 at 08:10