我会很快解释我想要做什么。我有一个自定义listView
,其中填充了SQLite
数据库中的数据。一旦列表项被长按,它就被添加到收藏夹:我在数据库中有一个单独的列,其中为添加到收藏夹的条目分配了“1”。到目前为止一切都还可以。
我现在要做的是用星星标记喜欢的列表项。我想对像SELECT text (id?) FROM info WHERE favourite = 1
这样的数据库进行查询,并在相应的列表项附近放置一个星号。问题是我不知道如何通过checkbox
(或position
?)调用特定列表项(text
?)并将其标记为已选中。我怎样才能做到这一点?
答案 0 :(得分:0)
此处带有复选框的CursorAdapter示例。
public class ItemCursorAdapter extends CursorAdapter {
private final LayoutInflater inflater;
private int itemNameIndex;
private int itemCheckIndex;
private DBHelper dbHelper;
public ItemCursorAdapter(Context context, Cursor cursor, boolean autoRequery) {
super(context, cursor, autoRequery);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemNameIndex = cursor.getColumnIndex(DBHelper.ITEM.NAME);
itemCheckIndex = cursor.getColumnIndex(DBHelper.ITEM.CHECK);
dbHelper = DBHelper.getInstance(context);
}
public void bindView(View view, Context context, Cursor cursor) {
String name = cursor.getString(itemNameIndex);
boolean checked = cursor.getInt(itemCheckIndex) > 0;
TextView nameTxt = (TextView) view.findViewById(R.id.item_name);
CheckBox checkChk = (CheckBox) view.findViewById(R.id.item_check);
checkChk.setOnCheckedChangeListener(new onItemCheckChangeListener(name));
nameTxt.setText(name);
checkChk.setChecked(checked);
}
@Override
public View newView(Context context, Cursor c, ViewGroup parent) {
View view = inflater.inflate(R.layout.row_item, null);
return view;
}
private class onItemCheckChangeListener implements OnCheckedChangeListener {
private String itemName;
public onItemCheckChangeListener(String itemName) {
this.itemName = itemName;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
dbHelper.changeItemCheck(itemName, isChecked);
}
}
}
And here example of table inside DBHelper
public static interface ITEM extends BaseColumns {
String TABLE_NAME = "itemTable";
String NAME = "itemName";
String CHECK = "itemCheck";
}
Method to get cursor for list
public Cursor getAllItemCursor() {
return getReadableDatabase().rawQuery("SELECT * FROM " + ITEM.TABLE_NAME, null);
}
and to update checkbox status to db
public void changeItemCheck(String itemName, boolean isChecked) {
ContentValues values = new ContentValues();
values.put(ITEM.CHECK, isChecked);
getWritableDatabase().update(ITEM.TABLE_NAME, values, ITEM.NAME + " =? ", new String[] { itemName });
}