我在閱讀了很多關於AsyncTask的同時嘗試使它與我的ListFragment一起工作。現在我遇到了幾篇文章,說由於技術原因它必須是靜態的。其他文章說,這並不重要,至於我的情況,我不能爲靜態做出正確的語法,所以我讓我的類非靜態的。如果建議將其設爲靜態,請幫助我改變它。AsyncTask應該是靜態的還是不重要?
我的課:
private class MyAsyncTask extends AsyncTask<List<String>, Void, List<String>>
{
// List of messages of the rss feed
private List<Message> messages;
private WeakReference<NieuwsSectionFragment> fragmentWeakRef;
private MyAsyncTask(NieuwsSectionFragment fragment)
{
this.fragmentWeakRef = new WeakReference<NieuwsSectionFragment>(fragment);
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
// progress.setVisibility(View.VISIBLE); //<< set here
}
@Override
protected List<String> doInBackground(List<String>... urls)
{
FeedParser parser = FeedParserFactory.getParser();
messages = parser.parse();
List<String> titles = new ArrayList<String>(messages.size());
for (Message msg : messages)
{
titles.add(msg.getTitle());
// Log.w("doInBackground", msg.getTitle());
}
return titles;
}
@Override
protected void onPostExecute(List<String> result)
{
super.onPostExecute(result);
if (result != null)
{
PostData data = null;
listData = new PostData[result.size()];
for (int i = 0; i < result.size(); i++)
{
data = new PostData();
data.postTitle = result.get(i);
listData[i] = data;
Log.w("onPostExecute", "" + listData[i].postTitle);
}
Log.w("onPostExecute", "" + adapter);
adapter = new PostItemAdapter (getActivity(), android.R.layout.simple_list_item_1, listData);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
當我讓靜態的它給人的適配器上的錯誤。它說了關於setListAdapter和getActivity()的一些東西。
是asynctask活動的內部類嗎? – Raghunandan
不,它是ListFragment的內部類 – Shishi
http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html。向下滾動並檢查點,並閱讀http://stackoverflow.com/questions/3106912/why-does-android-prefer-static-classes – Raghunandan