开发者

Android Async Task dealing with UI

开发者 https://www.devze.com 2023-03-18 22:08 出处:网络
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 js

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

精彩评论

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