I fixed my Android code but I want to know what was wrong with the old version

106 views Asked by At

I have a listview containing checkbox and textview and I've added a ViewBinder to my adapter and in this viewbinder I've added an onchecked state listener to my checkboxes and in the onchecked state listener I wrote this code:

OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String id=buttonView.getTag()+"";
                int buttonid=Integer.valueOf(id);               
                if(buttonView.isChecked()==true){   
                    Log.d("checked","checked");
                myDbHelper.MarkAsFavorite(buttonid);

                }

                else if(buttonView.isChecked()==false){
                    Log.d("unchecked","unchecked");
                    myDbHelper.UnMarkAsFavorite(buttonid);
                }

                 cu=myDbHelper.GetCursor();
                 adapter.swapCursor(cu);

            }
        }; 

but with this code when my check box was getting checked it was saved in the database then when I scroll through the listview it gets unchecked all byitself it accesses the code of the unchecked and unchecks the checkbox and save that in the database.

So I fixed it with adding an onclick listener to the checkbox instead of the onchange state listener:

public void onclick(View view) {
         String id=view.getTag()+"";
            int buttonid=Integer.valueOf(id);               
            if(((CompoundButton) view).isChecked()==true){  
                Log.d("checked","checked");
            myDbHelper.MarkAsFavorite(buttonid);

            }

            else if(((CompoundButton) view).isChecked()==false){
                Log.d("unchecked","unchecked");
                myDbHelper.UnMarkAsFavorite(buttonid);
            }

             cu=myDbHelper.GetCursor();
             adapter.swapCursor(cu);
     }

And I have no more problem. But I wanted to know why this change state listener acted that way?

2

There are 2 answers

9
vipul mittal On BEST ANSWER

You have this checkbox inside ListView as ListView reuses the views for efficiency same checkbox object may provided to multiple ListView items and when it is checked for same check box is unchecked for another.

1
Gaurav Berry On

This change state listener acted that ways then only when you scroll a listview because its getview call again which changes the checked check box state therefore checkchangedlistner call which changes value in database. And when you used onclick your problem resolved because on you changes listview view onclick event not fires which is not changing your database value.

You can resolve this problem by using viewholder in listview.