2

I am trying to write a AsyncTask generic package. Till now, what I've done is call one activity from another send the instance in the Intent to that Activity. This activity is part of the AsyncTask which calls the AsyncLoader.execute() file. I am doing this so that I don't lose any data that the parent Activity sets on the layout.

The other way to do it would be to call the Intent and return the data from the AsyncActivity to the parent Activity. But, both of these methods are slower than implementing the AsyncTask in the parent activity.

But, that clutters up the code. Thus, is there a better way of implementing it?

Hick
  • 35,524
  • 46
  • 151
  • 243

1 Answers1

3

It sounds like your tight-coupling between the activity and the AsyncTask is causing you issues that you're trying to overcome with a weird workaround.

In my experience the best way to design activities that need an AsyncTask is:

  • Keep your AsyncTask out of your activity, i.e. make a separate class that extends AsyncTask. This allows you to reuse the AsyncTask between multiple activities and make it easier to test.
  • If you need to return data back to your activity, use the listener and implement the listener on your activity. Then pass your listener to a class that creates the AsyncTask.

Passing of data between intents should be kept to a minimum, if you need to reuse the same AsyncTask from a separate activity you should follow the steps above and execute the task again. If you're going to be calling this through the lifecycle of the app, then consider using a service instead.

James Goodwin
  • 7,360
  • 5
  • 29
  • 41
  • I am passing a lot of data among Intents, in various other ways. Is that a bad way of doing it? – Hick Mar 03 '12 at 17:42
  • you should only be passing simple domain objects between classes (i.e. classes that just encapsulate data) not complex objects to perform tasks. The intent is just there to provide the data needed, but shouldn't decide how the data is used - that should be the activities responsibility. – James Goodwin Mar 03 '12 at 17:53
  • Personally I would always consider isolating AsyncTask from Activity as a bad re-factoring practice. by doing this, you ending with adding complexity to your code (passed in/out Context between classes), without gaining the real benefit of reusability and testability. Check out my answer [here](http://stackoverflow.com/questions/8295003/best-way-to-manage-the-progressdialog-from-asynctask/8317071#8317071) to see how to re-factoring your code in a more OO style way. – yorkw Mar 03 '12 at 22:41
  • 1
    Your not passing Context between classes, only the listener so your AsyncTask doesn't need to know about the activity that called it. I still think separating your business logic from the AsyncTask is a good idea though. – James Goodwin Mar 03 '12 at 22:48