简体   繁体   中英

Why does resetting my Adapter not take a new ArrayList?

i am trying to implement an option to hide certain items from an ArrayList "mTaskList".

For that, i provide a boolean "hideDues" in the Adapter's Constructor. If it is true, i filter these items out of the list.

public DeadlinesAdapter(Context context, ArrayList<TaskItem> taskList, DeadlinesAdapterListener listener, boolean hideDues) {
    if (hideDues) {
        for (int i = 0; i < taskList.size(); i++) {
            if (taskList.get(i).getTimeLeftInMinutes() < 1) taskList.remove(i);
        }
    }
    mTaskList = taskList;
    mContext = context;
    mListener = listener;
}

It works, but when i set that boolean to false and reset the adapter, it still uses the filtered list, even though the original ArrayList i provide in the Constructor, is unchanged.

if (mHideDues) {
                mHideDues = false;
                item.setIcon(R.drawable.ic_invisible_white);
            } else {
                mHideDues = true;
                item.setIcon(R.drawable.ic_visible_white);
            }

            mDeadlinesAdapter = new DeadlinesAdapter(this, mTaskList, this, mHideDues);
            mDeadlinesRecyclerView.setAdapter(mDeadlinesAdapter);

I change the boolean and reset the Adapter. mTaskList shouldnt have any changes. So why doesnt it take a new ArrayList?

You have to copy your ArrayList like this for example:

ArrayList newList = new ArrayList(oldList);

And only then pass it to the DeadlinesAdapter . It should solve your problem.

Sergei pointed to the problem: You are passing the list of tasks to your adapter, where you filter the list. Now what you probably want to do is filter a copy of the list. What you actually do is remove the items from the original list. That's why when you set mHideDues to false, nothing happens.

What you can do is simply:

ArrayList<TaskItem> mTaskList = new ArrayList<TaskItem>();

public DeadlinesAdapter(Context context, ArrayList<TaskItem> taskList, DeadlinesAdapterListener listener, boolean hideDues) {

    mTaskList.addAll(taskList);

    if (hideDues) {
        for (int i = 0; i < this.list.size(); i++) {
            if (mTaskList.get(i).getTimeLeftInMinutes() < 1) mTaskList.remove(i);
        }
    }

    mContext = context;
    mListener = listener;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM