Sunday, October 25, 2015

Cursor adapter for a custom list view with checkboxes

public class TasksCursorAdapter_CA extends android.widget.CursorAdapter {


SQLiteDatabase dh = DatabaseHelper_CA.getInstance().getDb();
private LayoutInflater mInflater;
private Context mContext;
Cursor cursor;

public TasksCursorAdapter_CA(Context context, Cursor c) {
super(context, c);

mInflater = LayoutInflater.from(context);
mContext = context;
cursor = c;
}

@Override
public void bindView(View view, Context context, final Cursor cursor) {

ViewHolder_CA holder = (ViewHolder_CA) view.getTag();

holder.setTextView((TextView) view.findViewById(R.id.textviewx));
holder.setCheckBox((CheckBox) view.findViewById(R.id.checkbox));
CheckBox cb = holder.getCheckBox();

holder.getTextView().setText(cursor.getString(cursor.getColumnIndex("name")));

cb.setTag(new Integer(cursor.getPosition()));

CompoundButton.OnCheckedChangeListener checkedChange = new CompoundButton.OnCheckedChangeListener() {

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


ContentValues contentValues = new ContentValues();

Integer currentPosition = (Integer) buttonView.getTag();

String currentPositionString = Double.toString(currentPosition);
if (cursor.moveToPosition(currentPosition)) {

String rowID = cursor.getString(cursor.getColumnIndex("_id"));
if (isChecked) {
contentValues.put("selected", "1");
dh.update(DatabaseHelper_CA.TABLE_NAME, contentValues, "_id = ?",
new String[]{rowID});

} else if (!isChecked) {
contentValues.put("selected", "0");
dh.update(DatabaseHelper_CA.TABLE_NAME, contentValues, "_id = ?",
new String[]{rowID});
}

}

}
};
cb.setOnCheckedChangeListener(checkedChange);

if (cursor.getString(cursor.getColumnIndex("selected")).compareTo("1") == 0) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {

ViewHolder_CA holder;
View convertView = mInflater.inflate(R.layout.custom_ca, parent, false);
holder = new ViewHolder_CA(convertView);
convertView.setTag(holder);
return convertView;
}

}

No comments:

Post a Comment