问题描述
我有一个包含一些数据的XML文件,所以我创建了一个类重presenting是:
I have a XML file containing some data, so I created a class representing it :
public class MyData
{
ArrayList<SpecialData> list;
int currentPage, totalPages;
}
正如您可以猜到我有 SpecialData code>的项目,每一个都包含许多领域,列表和
当前页
/ 总页数
是XML文件中的两个独特的价值。我需要和异步解析XML文件,所以我创建了这个类:
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;
}
}
我给它一个尝试,这个问题并非来自这里,因为我正确地分析我的XML文件和我的迈德特
对象是完美的。但后来我用这个任务,这样在我的主活动
类:
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?
这可能是非常愚蠢的,但我根本不知道怎么我的迈德特
实例从我的主类链接到一个我与的AsyncTask 。我该怎么办?谢谢你。
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.
推荐答案
覆盖的AsyncTask
的 onPostExecute
方法:
protected void onPostExecute(MyData result) {
md = result;
}
请注意,这里假设你的AsyncTask是一个内部类中的活动。如果不是的话,你可以在构造函数中的AsyncTask的参考,你的活动通过。在这种情况下,你应该小心使用的WeakReference
你的活动,以prevent资源泄漏:
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);
}
这篇关于需要说明:如何使用AsyncTask的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!