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 parsexmland receivejsonby requesting to web service and starts aProgressDialog. - The class performs
xmlandjsonparsing in itsdoInBackgroundmethod. - In the
onPostExecutemethod after p开发者_Go百科arsing is complete, dismiss theProgressDialogthat 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
onPostExecutemethod.
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:
- Define a call-back interface (let's call it
WorkDoneListener) with a single method:workDone(). - Declare your activity class to implement
WorkDoneListenerand implementworkDone()to dismiss the dialog. - Define the AsyncTask's constructor to accept a
WorkDoneListener. Stash the reference in a member field. - In
onPostExecute, call the listener'sworkDone()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.
加载中,请稍侯......
精彩评论