0
這是我的問題。我有一個AsyncTask代碼如下:在刷新時處理AsyncTask複製項目
private class BackgroundAsyncTask extends AsyncTask<String, Void, Integer> {
OkHttpUtil okHttp = new OkHttpUtil();
private static final int RESULT_FAILURE = 0;
private static final int RESULT_SUCCESS = 1;
private static final int RESULT_DATA_ADDED = 2;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ARRAY = "articles";
private static final String url = "http://x/db/fetch_all.php";
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(true);
}
}
@Override
protected Integer doInBackground(String... params) {
int result = 0;
try {
JSONObject jsonObject = new JSONObject(okHttp.okHttpGet(url));
result = jsonObject.optInt(TAG_SUCCESS);
if (result == RESULT_SUCCESS) {
JSONArray jsonArray = jsonObject.optJSONArray(TAG_ARRAY);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonArticle = jsonArray.optJSONObject(i);
int id = jsonArticle.optInt(NewsletterHContract.FavoritesColumns.ID);
String img = jsonArticle.optString(NewsletterHContract.FavoritesColumns.IMG);
String title = jsonArticle.optString(NewsletterHContract.FavoritesColumns.TITLE);
String content = jsonArticle.optString(NewsletterHContract.FavoritesColumns.CONTENT);
mArticleList.add(new Article(id, img, title, content));
result = RESULT_DATA_ADDED;
}
}
} catch (Exception e) {
Timber.e(e, "Error parsing JSON Object");
}
return result;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == RESULT_DATA_ADDED) {
mRecyclerView.getAdapter().notifyDataSetChanged();
}
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
}
AsyncTasks碰巧對我來說很新。現在是用戶刷新時,我正在執行new BackgroundAsyncTask().execute()
。
這樣做會再次將相同的內容添加到我的RecyclerView中。有一些方法可以讓我完成這些事情:
- 檢測不與數組列表的所有項目比較當前獲取的項目要知道,如果數據是陳舊的添加新的數據。
- 防止在屏幕方向更改時再次運行AsyncTask。
讓我來提一下,我正在執行片段的onCreateView()
中的AsyncTask。