Skip to content Skip to sidebar Skip to footer

Need An Explanation : How To Use Asynctask?

I have a XML file containing some data, so I created a class representing it : public class MyData { ArrayList list; int currentPage, totalPages; } As y

Solution 1:

Override AsyncTask's onPostExecute method:

protectedvoidonPostExecute(MyData result) {
     md = result;
 }

Note that this assumes your AsyncTask is an inner class to your activity. If that isn't the case, you can pass in a reference to your Activity in the constructor to your AsyncTask. In those cases, you should be careful to use a WeakReference to your Activity to prevent resource leaks:

GetXMLTask(MyActivity activity)
{
    this.mActivity = new WeakReference<MyActivity>(activity);
}

protectedvoidonPostExecute(MyData result)
{
     MyActivity activity = this.mActivity.get();
     if (activity == null) // Activity was destroyed due to orientation change, etc.return;
     activity.updateUiFromXml(result);
 }

Solution 2:

You probably want to implement a callback of some sort. This way you avoid exposing your data by making it publicly accessible, and you can implement other callbacks (such as an error callback if there is a problem loading the data).

For example, you could define an interface like this:

interfaceMyAsyncFinishedLister {
    voidonFinished(MyData resultData);
}

Your AsyncTask will have an instance of MyAsyncFinishedListener, and you can call in onPostExecute as so:

protectedvoidonPostExecute(MyData result) {
     myAsyncFinishedListener.onFinished(result);
}

Your main activity will implement this interface and look something like:

classMyActivityextendsActivityimplementsMyAsyncFinishedListener {
    MyData md;

    publicvoidonCreate() {
        super.onCreate();

        GetXMLTask task = newGetXMLTask(this);
        task.execute(newString[]{url});
        task.setOnFinishedListener(this);
    }

    onFinished(MyData result) {
        md = result;
    }
}

Solution 3:

If you want an AsyncTask to return a data object, you need to store it in a variable in class scope, not function scope. To make this easy, the task is usually a private inner class.

Solution 4:

Declare MyData as a variable visible to the whole class and try to access it in onPostExecute() by assigning the result to the MyData variable.

Post a Comment for "Need An Explanation : How To Use Asynctask?"