I have a XML file containing some data, so I created a class representing it :
public class MyData
{
ArrayList<SpecialData> list;
int currentPage, totalPages;
}
As you can guess I have a list of SpecialData items, each one containing many fields, and currentPage/totalPages are two unique values in the XML file. I need to get and parse the XML file asynchronously, so I created this class :
class GetXMLTask extends AsyncTask<String, Void, MyData>
{
@Override
protected MyData doInBackground(String... params)
{
MyData md = null;
// Getting/parsing data
return md;
}
}
I gave it a try and the problem doesn't come from here because I correctly parse my XML file and my MyData object is perfect. But then I use this task like this in my main Activity class :
MyData md = null;
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[]{url});
// How can this change my md object?
This may be very silly but I simply don't know how to link my MyData instance from my main class to the one that I get with AsyncTask. What should I do? Thanks.
Override AsyncTask's onPostExecute method:
protected void onPostExecute(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);
}
protected void onPostExecute(MyData result)
{
MyActivity activity = this.mActivity.get();
if (activity == null) // Activity was destroyed due to orientation change, etc.
return;
activity.updateUiFromXml(result);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With