Listview中的CursorAdapter

ham*_*djj 10 checkbox android listview android-cursoradapter

我正在使用CursorAdapter在listview中读取数据库.我在列表的每个项目中都有一个复选框,当用户选中复选框时,我的数据库中的收藏列会更改是,并且项目会添加到收藏夹中.

一切都很好,最喜欢的列已更改,但当我在列表中向上和向下滚动时,复选框将取消选中.如果您重新启动应用程序,则复选框已被选中

我该怎么办这个问题:

对不起,我的英语不好:

CursorAdapter类:

public class MyAdapter extends CursorAdapter {

    Context b;   
    LayoutInflater inflater;
    @SuppressWarnings("deprecation")
    public MyAdapter(Context context, Cursor c) {
        super(context, c);
        inflater = LayoutInflater.from(context);
        b= (Context) context;
    }

    @SuppressWarnings("unused")
    @Override
    public void bindView(View view, Context context, final Cursor cursor) {
        // TODO Auto-generated method stub

        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 me = cursor.getString(cursor.getColumnIndex("like"));

        if (me.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()) {                   
                    mydb.execSQL("update list set like = 'yes' where id = " + cursor.getString(1));

                }else{
                    mydb.execSQL("update list set like = 'no' where id = " + cursor.getString(1));           

                }
            }
        });

        }

        protected Context getActivity() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return inflater.inflate(R.layout.item, parent, false);
        }
    }
Run Code Online (Sandbox Code Playgroud)

截图:

在此输入图像描述

max*_*max 2

问题是当您更新数据库时,只是数据库要更新而不是适应游标适配器的游标,因此您必须使用

 changeCursor(newcursor);
Run Code Online (Sandbox Code Playgroud)

更新数据库后在您的适配器中。希望这对你有帮助。