Checkbox in CursorAdapter

I read this post

but I can not solve my problem. I am using CursorAdapter in listview.

I have a checkbox in each element of the list. If you check the box and scroll up and down. the checkbox will be disabled. I can’t fix it. please help me.

@Override public void bindView(View view, Context context, final Cursor cursor) { TextView tv1 = (TextView)view.findViewById(R.id.txt_name); TextView tv2 = (TextView)view.findViewById(R.id.txt_numer); tv1.setText(cursor.getString(2)); tv2.setText(cursor.getString(3)); final int pos = cursor.getPosition(); final CheckBox repeatChkBx = (CheckBox)view.findViewById(R.id.favorite_check); String likes = cursor.getString(cursor.getColumnIndex("like")); if (likes.equals("yes")) { repeatChkBx.setChecked(true); } else { repeatChkBx.setChecked(false); } repeatChkBx.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { MyDatabase mydatabase = new MyDatabase(b); SQLiteDatabase mydb = mydatabase.getWritableDatabase(); cursor.moveToPosition(pos); if (repeatChkBx.isChecked()) { ContentValues cv = new ContentValues(); cv.put("like", "yes"); mydb.update("list", cv, "id ="+cursor.getString(1), null); } else { ContentValues cv = new ContentValues(); cv.put("like", "no"); mydb.update("list", cv, "id ="+cursor.getString(1), null); } mydb.close(); } }); } 

i using an external database and a column to save a favorite item.

+6
source share
1 answer
 if (likes.equals("yes")) { repeatChkBx.setChecked(true); } else { repeatChkBx.setChecked(false); } 

Here you set the CheckBox token again and again when the bindView is called after scrolling through the ListView. User selection is not remembered and reset in CheckBox. You need to remember the custom choice of CheckBox and set it to bindView.

+2
source

Source: https://habr.com/ru/post/969541/


All Articles