Hoo Hoo - 15 days ago 7
Android Question

Reset counter after button click

In DeleteTask, I have a button used to delete the list if checkbox is checked in the listView.

delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

int itemCount = listview.getCount();
for (int i = itemCount - 1; i >= 0; i--) {
SearchList search = adapter.getItem(i);
if (search.isSelected()) {
adapter.removeItem(i);
delete.setText("DELETE");
counter=0;
}
}
}
});


In DeleteAdapter, it has a counter used to count the checked box and display the counter in
button
. Once the delete
button
is clicked, the counter suppose reset to 0 and only shows
DELETE
in delete
button
setText.

holder.ckbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
int getPosition = (Integer) v.getTag(); // Here we get the position that we have set for the checkbox using setTag.
search.get(getPosition).setSelected(((CheckBox)v).isChecked()); // Set the value of checkbox to maintain its state.
checkBoxCounter ++;
delete.setText("DELETE"+""+"("+ checkBoxCounter +")");
} else
{
int getPosition = (Integer) v.getTag(); // Here we get the position that we have set for the checkbox using setTag.
search.get(getPosition).setSelected(((CheckBox) v).isChecked()); // Set the value of checkbox to maintain its state.
checkBoxCounter--;
if (checkBoxCounter == 0) {
delete.setText("DELETE");
}
else {
delete.setText("DELETE" + "" + "(" + checkBoxCounter + ")");
}
}
}
});


My problem now is when the delete button is clicked, it show 'DELETE', but when I check the checkBox, the counter did not reset. How to reset the counter ?

Edit

I have change the counter to checkBoxCounter, but still getting the same result ! 

delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

int itemCount = listview.getCount();
for (int i = itemCount - 1; i >= 0; i--) {
SearchList search = adapter.getItem(i);
if (search.isSelected()) {
adapter.removeItem(i);
delete.setText("DELETE");
checkBoxCounter=0;
}
}
}
});



When I click
button
delete, the button shows
DELETE
. But, when I
press another checkbox again, the counter starts from the last set
value instead of 1.


Please help.

Here are part of my app screen shot

https://i.stack.imgur.com/R954N.jpg

Answer

If there are two different classes, then add a method inside the adapter class to reset the counter.

May be like this:

  1. Inside adapter class, add:

    public void resetCheckedCounter(){
        checkBoxCounter = 0;
    }
    
  2. For the "Delete" button, add:

    adapter.resetCheckedCounter();
    

Hope this help!