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 parsexml
and receivejson
by requesting to web service and starts aProgressDialog
. - The class performs
xml
andjson
parsing in itsdoInBackground
method. - In the
onPostExecute
method after p开发者_Go百科arsing is complete, dismiss theProgressDialog
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:
- Define a call-back interface (let's call it
WorkDoneListener
) with a single method:workDone()
. - Declare your activity class to implement
WorkDoneListener
and 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.
精彩评论