我正在使用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);
        }
    }

截图:

最佳答案

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

 changeCursor(newcursor);

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

07-24 09:47
查看更多