开发者

Android Async Task dealing with UI

I am new to android development. I would like to accomplish a task described as follows:

  • A main activty which calls external class(the other class would extend AsyncTask) to parse xml and receive json by requesting to web service and starts a ProgressDialog.
  • The class performs xml and json parsing in its doInBackground method.
  • In the onPostExecute method after p开发者_Go百科arsing is complete, dismiss the ProgressDialog that was set in the main activity.
  • I could do this by passing the ProgressDialog object to the parsing class and dismissing the same object in its onPostExecute method.

I think passing an instance of UI object as argument is not a good approach to program, I hope there must be some other ways to work around.

Please suggest. Thank you


The easiest way to decouple these is to use an interface:

  1. Define a call-back interface (let's call it WorkDoneListener) with a single method: workDone().
  2. Declare your activity class to implement WorkDoneListener and implement workDone() to dismiss the dialog.
  3. Define the AsyncTask's constructor to accept a WorkDoneListener. Stash the reference in a member field.
  4. In onPostExecute, call the listener's workDone() method.


Ted's answer is what you should do if your AsyncTask is too big and you want to declare it in other file. However, keep in mind that usually you declare the AsyncTask inside your UI class:

public class YourActivity extends Activity{
    private class YourAsyncTask extends AsynkTask<etc.>{
    }
}

In fact, if you are using you AsyncTask from that activity only (I mean, if you are not using it anywhere else), declaring the AsyncTask as a inner class is a good design practice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜