Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If AsyncTask is not an inner class... - some questions

1) I don't underestand why the samples of Android almost use AsyncTasks as private inner classes. I know it is convenient to make it inner class but it makes our class file longer and hard to read. ShelvesActivity of Shelves sample application have even 845 lines. Don't you think it is a bad design or bad construction?

2) If I make my ScanStorageTask external class, what do I have to pass to it? entire Activity or only used widgets?

Example: If I must use a WebView, a Button and a ProgressBar in ScanStorageTask. I use this:

ScanStorageTask task = new ScanStorageTask(this); // "this" is activity reference, then get the webView, button, progressBar from it.

or this:

ScanStorageTask task = new ScanStorageTask(webView, button, progressBar);
like image 522
emeraldhieu Avatar asked Aug 26 '11 14:08

emeraldhieu


1 Answers

There's nothing wrong with doing it externally, and it actually might be a better design. Passing UI elements around is the kind of tight coupling that can get you into trouble when you have a really large code base anyway.

Why not do it externally and use the "listener" pattern that the UI controls employ? Make your ScanStorageTask its own class, create an OnCompleteListener interface with an onComplete method, and pass that to your ScanStorageTask instance (expose a setOnCompleteListener method or something to that effect). Then, onPostExecute can just do this:

if(onCompleteListener != null)
  onCompleteListener.onComplete(data);

That way, you define your UI updates inside your activity based on the data. It's better separation of concerns and will keep your lines of code per class down, as that seems to be what you'd prefer. If you don't already have this, make a class that represents the data you need to pass in and get out, and that's what you pass in to the task as a param to the execute method and what onPostExecute passes to onComplete.

like image 107
Rich Avatar answered Sep 30 '22 23:09

Rich