我有一個AsyncTask刷新我的listView onPostExecute事件,並檢索doInBackground事件中的一些數據。問題是我的AsyncTask在onScroll事件中被多次執行。我怎樣才能防止它做到這一點?順便說一下,我試圖在我的應用程序中創建一個Inifinite Scroll。也許我做錯了什麼? 這裏是我的onScroll事件:如何防止AsyncTask在onScroll事件中被多次執行?
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
previousTotal = totalItemCount;
try {
itemNews = listAdapter.getData();
}catch (Exception e){
System.out.println("itemNews is empty");
}
if(totalItemCount > 2) {
artId = itemNews.get(firstVisibleItem).articleId;
}
if(firstVisibleItem > ((previousTotal)/2))
{
UpdateListAsyncTask updateListAsyncTask = new UpdateListAsyncTask(artId, mActivity, listAdapter);
updateListAsyncTask.execute();
}
而且這裏是我的AsyncTask:
public class UpdateListAsyncTask extends AsyncTask<Void, Void, Void> {
public int currentArticleId;
public Activity mActivity;
RemoteData remoteData;
public ListAdapterRegular listAdapter;
UpdateListAsyncTask(int currentArticleId, Activity activity, ListAdapterRegular listAdapterRegular)
{
this.mActivity = activity;
this.currentArticleId = currentArticleId;
this.listAdapter = listAdapterRegular;
}
@Override
protected void onPreExecute()
{
remoteData = new RemoteData(mActivity, "News");
}
@Override
protected Void doInBackground(Void... params) {
try{
remoteData.writeServerData("&from=" + currentArticleId);
System.out.println("DoInBackground writeServerData");
}catch (Exception e)
{
e.printStackTrace();
System.out.println("UpdateListAsyncTask: doInBackground exception!");
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
List<News> dataList = Select.from(News.class).orderBy("date DESC").list();
System.out.println("onPostExecuteInitiated");
listAdapter.clear();
listAdapter.addAll(dataList);
listAdapter.notifyDataSetChanged();
}
}
任何幫助和想法這麼多的讚賞! 更新: 我不得不重做我的代碼,但它值得。我根據鏈路做到了:https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews
條件是什麼防範? –
AsyncTask平均執行10次,直到用戶的手指離開屏幕。 – Rishka
我的意思是,每當用戶滾動屏幕時,「滾動條上防止觸發的條件是什麼」都會觸發。必須有一些檢查,以防止您的異步任務被解僱。 –