Home > Back-end >  onCheckedChanged is called whenever viewHolder is recycled
onCheckedChanged is called whenever viewHolder is recycled

Time:04-15

I am writing a todo list application and, in particular, I want the value of the checkBox to be stored in the database every time it is changed.

I set this feature by adding setOnCheckedChangeListener in onBindViewHolder

@Override
    public void onBindViewHolder(@NonNull TodosAdapter.TodoViewHolder holder, int position)
    {
        Todo todo = todoList.get(position);

        holder.todoTV.setText(todo.getText());
        holder.todoTV.setChecked(todo.isDone()); //isDone is a boolean that indicates whether the checkBox has been selected or not

        holder.todoTV.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                dbManager.allDao().setTodoIsDone(todo.getTodoId(), isChecked); //sets the isDone attribute of the database
                todo.setDone(isChecked);
            }
        });
    }

The problem is that onCheckedChanged is also called when the viewHolder is recycled and in these cases it returns isChecked = false;

enter image description here

CodePudding user response:

I found the solution here:Android setOnCheckedChangeListener calls again when old view comes back. Just use the buttonView.isShown() method:

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if(buttonView.isShown()) {
        dbManager.allDao().setTodoIsDone(todo.getTodoId(), isChecked); //sets the isDone attribute of the database
        todo.setDone(isChecked);
    }
}
  • Related