AsyncTask执行两次

时间:2018-02-01 16:02:35

标签: android android-asynctask

我有两个RecyclerView的布局,我为每个执行一个AsyncTask。但AsyncTask每次执行两次。

我看不到任何错误,我已经调试过,并检查过每个AsynTask执行两次。

我还检查了如果我删除了方法setListeners(),我在其中实现onScrollListeners,两个RecyclerView没有执行两次。

当声明监听器时,应该不执行,对吧?

片段:

public class TasksFragment extends Fragment implements TaskAdapter.ListItemClickListener {
    private JSONObject token;
    private ProgressBar pbLoadingTasks, pbLoadingExams;
    private ArrayList<SchoolNotification> exams = new ArrayList();
    private ArrayList<SchoolNotification> tasks = new ArrayList();
    private ArrayList<TasksList> tasksLists = new ArrayList<>();
    private ArrayList<TasksList> examsLists = new ArrayList<>();
    private TasksListAdapter tasksAdapter, examsAdapter;
    private RecyclerView rvTasksList, rvExamsList;
    private Integer indexTasks = 0;
    private Integer indexExams = 0;
    private Integer paginationTasks = 0;
    private Integer paginationExams = 0;
    private boolean reload = false;

public static TasksFragment newInstance() {
    TasksFragment fragment = new TasksFragment();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_tasks, container, false);

    token = ((MainActivity) getActivity()).getToken();

    rvTasksList = (RecyclerView) view.findViewById(R.id.rv_tasks);
    rvExamsList = (RecyclerView) view.findViewById(R.id.rv_exams);
    pbLoadingExams = (ProgressBar) view.findViewById(R.id.pb_loading_exams);
    pbLoadingTasks = (ProgressBar) view.findViewById(R.id.pb_loading_tasks);

    LinearLayoutManager tasksLayoutManager = new LinearLayoutManager(getActivity());
    rvTasksList.setLayoutManager(tasksLayoutManager);
    rvTasksList.setHasFixedSize(true);
    tasksAdapter = new TasksListAdapter(getActivity(), tasksLists, TasksFragment.this);
    rvTasksList.setAdapter(tasksAdapter);


    LinearLayoutManager examsLayoutManager = new LinearLayoutManager(getActivity());
    rvExamsList.setLayoutManager(examsLayoutManager);
    rvExamsList.setHasFixedSize(true);
    examsAdapter = new TasksListAdapter(getActivity(), examsLists, TasksFragment.this);
    rvExamsList.setAdapter(examsAdapter);

    requestTasks();
    requestExams();

    setListeners();

    return view;
}

private void setListeners() {
    rvExamsList.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
        @Override
        public void onLoadMore() {
            requestExams();
        }
    });

    rvTasksList.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
        @Override
        public void onLoadMore() {
            requestTasks();
        }
    });
}

private void classifyTasks() {

    if (tasks.size() > 0) {
        TasksList task = new TasksList();

        task.setDate(tasks.get(0).getDate());
        for (SchoolNotification n : tasks) {
            if (n.getDate().equals(task.getDate())) {
                task.getTasks().add(n);
            } else {
                tasksLists.add(task);
                task = new TasksList();
                task.setDate(n.getDate());
                task.getTasks().add(n);
            }
        }
        tasksLists.add(task);
    }
}

private void classifyExams() {

    if (exams.size() > 0) {
        TasksList exam = new TasksList();

        exam.setDate(exams.get(0).getDate());
        for (SchoolNotification n : exams) {
            if (n.getDate().equals(exam.getDate())) {
                exam.getTasks().add(n);
            } else {
                examsLists.add(exam);
                exam = new TasksList();
                exam.setDate(n.getDate());
                exam.getTasks().add(n);
            }
        }
        examsLists.add(exam);
    }
}

private void indexTasks() {
    Calendar cal = Calendar.getInstance();

    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);

    Date midnight = cal.getTime();

    for (int i = 0; i < tasksLists.size(); i++) {
        TasksList t = tasksLists.get(i);
        if (t.getDate().after(midnight)) {
            indexTasks = i;
        } else {
            indexTasks += 1;
            break;
        }
    }
}

private void indexExams() {
    Calendar cal = Calendar.getInstance();

    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);

    Date midnight = cal.getTime();

    for (int i = 0; i < examsLists.size(); i++) {
        TasksList t = examsLists.get(i);
        if (t.getDate().after(midnight)) {
            indexExams = i;
        } else {
            indexExams += 1;
            break;
        }
    }
}

@Override
public void onListItemClick(SchoolNotification notification) {

    reload = true;

    NotificationDetailFragment detailFragment = NotificationDetailFragment.newInstance();
    Bundle bundle = new Bundle();
    bundle.putParcelable("notification", notification);
    detailFragment.setArguments(bundle);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_layout, detailFragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

}

private void requestTasks() {

    new notificationsTask(StaticConfiguration.TASK).execute();
}

private void requestExams() {

    new notificationsTask(StaticConfiguration.EXAM).execute();
}

public class notificationsTask extends AsyncTask<Boolean, Void, Boolean> {

    String type;
    Integer pagination;
    ArrayList<SchoolNotification> requestedNotifications = new ArrayList<>();

    public notificationsTask(String type){
        this.type = type;
    }

    @Override
    protected Boolean doInBackground(Boolean... params) {
        try {

            if (type.equals(StaticConfiguration.TASK)){
                pagination = paginationTasks;
            }else{
                pagination = paginationExams;
            }

            JSONArray response = NetworkUtils.schoolNotifications(token, 40, pagination, null, null, StaticConfiguration.ORDER_DATE_DESC, null, null, type);
            requestedNotifications = Utils.parseNotificationsResponse(response);
            pagination += 40;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    @Override
    protected void onPreExecute() {
        if (type.equals(StaticConfiguration.TASK))
            pbLoadingTasks.setVisibility(View.VISIBLE);
        else
            pbLoadingExams.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        if (type.equals(StaticConfiguration.TASK)){
            tasks.addAll(requestedNotifications);
            tasksAdapter.notifyDataSetChanged();
            classifyTasks();

            if (paginationTasks == 0) {
                indexTasks();
                rvTasksList.scrollToPosition(indexTasks);
            }
            paginationTasks = pagination;
            pbLoadingTasks.setVisibility(View.INVISIBLE);

        }else{
            exams.addAll(requestedNotifications);
            examsAdapter.notifyDataSetChanged();
            classifyExams();
            if (paginationExams == 0) {
                indexExams();
                rvExamsList.scrollToPosition(indexExams);
            }
            paginationExams = pagination;
            pbLoadingExams.setVisibility(View.INVISIBLE);
        }
    }
}

EndlessRecyclerOnScrollListener:

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {

    private int mPreviousTotal = 0;
    private boolean mLoading = true;

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        int visibleItemCount = recyclerView.getChildCount();
        int totalItemCount = recyclerView.getLayoutManager().getItemCount();
        int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();

        if (mLoading) {
            if (totalItemCount > mPreviousTotal) {
                mLoading = false;
                mPreviousTotal = totalItemCount;
            }
        }
        int visibleThreshold = 5;
        if (!mLoading && (totalItemCount - visibleItemCount)
                <= (firstVisibleItem + visibleThreshold)) {
            // End has been reached

            onLoadMore();

            mLoading = true;
        }
    }

    public abstract void onLoadMore();
}

1 个答案:

答案 0 :(得分:0)

调用AsyncTask的

requestTasks();requestExams();也会在onCreateView中调用。因此,即使删除setListeners,也会调用Asynctask。