0

is it in general better to create AsyncTask as private class within an Activitiy, or rather separate them in an own class?

public class MyActivity extends Activity {
  private class DownloadPage extends AsyncTask {
  }
}
richarbernal
  • 1,063
  • 2
  • 14
  • 32
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • 1
    A private class within an activity would be more "readable"/logical in most cases, according to me – keyser May 19 '12 at 15:03
  • 1
    If you like code files consisting of >1000 lines, you can create private classes. But I prefer to create additional classes in separate files rather than to put everything in a single class. – vortexwolf May 19 '12 at 15:45

2 Answers2

2

AsyncTask inside Activity is more suitable after completing backgroud task you can change view easily.

In seperate class you need to pass context and its result comes in seperate class and then you have to get result from seperate class.

But seperate class is very useful sometimes when we need more asyncTask in application , and if you have large code in your activity so its better to use seperate class.

So AsyncTask is suitable inside Activity to interact with view...and seperate class is also suitable when we need more asynctask in application.

So its totally depends on requirements...

Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • you are right but if in case you need the same async task many times the better to have a class. – Shankar Agarwal May 19 '12 at 16:21
  • @SamirMangroliya Do you think its fine if I want to restructure... to move (Web service / XML HTTP calls) into separate class. I can then use a `callback listener Interface` in my parent `Class/Activity` which the child `onPostExecute` calls to notify the parent `Activity` that its complete. Is that something which is ok to use in Android design? thanks for your help. PS: the answer in this SO is what I have implemented (http://stackoverflow.com/questions/3291490/common-class-for-asynctask-in-android) – wired00 Nov 13 '12 at 23:46
1

A private class within the Activity has the access to all private members, including context, which greatly helps not only to do the job, but to show ProgressDialog as well.

lenik
  • 23,228
  • 4
  • 34
  • 43