Using an ArrayList to store the state of all the checkboxes in the list.
public static ArrayList<Boolean> hitList;
I have initialized and set all values to false:
hitList=new ArrayList<Boolean>();
for(int i=0;i<this.getCount();i++)
{
hitList.add(i, false);
}
When,initializing the checkbox for a View,it looks in the array by position and checks it only if the value in the ArrayList is true.The position is held by the CheckBox using it's setTag method and retrieved within the Listener to determine the position of the checkbox which has been checked.
@Override
public View getView(int position,View convertView,ViewGroup parent)
{
View row=convertView;
ViewHolder holder;
if(row==null)
{
row=inflater.inflate(layout, null, false);
holder=new ViewHolder(row);
row.setTag(holder);
holder.check_del.setTag(position);
}
else
{
holder=(ViewHolder)row.getTag();
holder.check_del.setOnClickListener(null);
holder.check_del.setTag(position);
if(hitList.get(position))
holder.check_del.setChecked(true);
else
holder.check_del.setChecked(false);
}
c.moveToPosition(position);
holder.txt_a.setText(c.getString(c.getColumnIndex(ItemDB.TITLE)));
holder.txt_b.setText(c.getString(c.getColumnIndex(ItemDB.DESCRIPTION)));
OnClickListener cbl=new OnClickListener(){
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
int position=(Integer)view.getTag();
Log.d("CustomCursorAdapter", "The checkbox at postion "+position+" has been clicked");
if(((CheckBox)view).isChecked())
{
hitList.set(position, true);
}
else
{
hitList.set(position, false);
}
}
};
holder.check_del.setOnClickListener(cbl);
return row;
}
static class ViewHolder
{
TextView txt_a;
TextView txt_b;
CheckBox check_del;
ViewHolder(View row)
{
txt_a=(TextView)row.findViewById(R.id.txt_a);
txt_b=(TextView)row.findViewById(R.id.txt_b);
check_del=(CheckBox)row.findViewById(R.id.check_del);
}
}
Currently,I have a header in the ListView which has the following onClickListener:
@SuppressWarnings("deprecation")
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
ArrayList<Boolean> killList=CustomCursorAdapter.hitList;
int totalDeleted=0;
for(int i=0;i<killList.size();i++)
{
//Log.d(TAG,i+":"+killList.get(i));
c.moveToPosition(i);
String title=c.getString(c.getColumnIndex(ItemDB.TITLE));
int _id=c.getInt(c.getColumnIndex(ItemDB._ID));
//Log.d(TAG, "Item has title "+title+" and id "+_id );
int rowsAffected=0;
if(killList.get(i))
{
rowsAffected=db.delete(_id);
//Log.d(TAG, "Deleted row with id "+_id);
killList.set(i, false);
}
totalDeleted+=rowsAffected;
}
//Log.d(TAG, "The total number of rows deleted "+totalDeleted);
//if(c.requery())
//{
//Log.d(TAG, "Requerying data,this calls notifyDataSetChanged");
//}
}});
Once,you have deleted data from the row,before you call requery on the Cursor(which is deprecated...need to find a better alternative),the values in the ArrayList have to be reset.