我正在使用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);
在更新数据库后在适配器中输入。希望对您有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句