且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Listview中的CursorAdapter

更新时间:2023-10-14 15:54:46

问题是当你更新你的数据库只是数据库更新不适应光标适配器的光标,所以你必须使用

  changeCursor(newcursor);更新数据库后,您的适配器中的


希望这有助于你。


i'm using CursorAdapter for reading database in listview. i have a checkbox in the each item of the list that when the checkbox was checked by user the favorite Column in my database change the yes and the item added to the favorite.

everything is ok and the favorite column changed but when i scroll up and down the list the checkbox going to unchecked. and if you restarting the app the checkbox have been checked

what should i do for this problem:

sorry for my bad english:

CursorAdapter class:

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);
        }
    }

screenshot:

problem is when you update your database just database going to update not cursor that adapt your cursor adapter ,so you have to use

 changeCursor(newcursor);

in your adapter after updating your database. hope this help you.