我创建了一个包含文本框和图像的自定义列表。图像应删除数据库 SQLite 中的行。
在我的 fragment Activity 中,我使用sqlitedatabase的查询方法。
cursor = mSqLiteDatabase.rawQuery("SELECT liked_id as _id, liked_presentation_id FROM liked", null);
LikedListCursorAdapter likedListCursorAdapter = new LikedListCursorAdapter(getActivity(), cursor);
lvItems.setAdapter(likedListCursorAdapter);
/////////////我的光标适配器
public class LikedListCursorAdapter extends CursorAdapter {
SQLiteDatabase mSqLiteDatabase;
int idSpeaker,idPresentation;
TextView textViewName, textViewCompany, textViewTitle, textViewDate, textViewAboutReport;
LinearLayout linearLayout;
public static ImageView imageViewStatus;
private DatabaseHelper mDatabaseHelper;
public LikedListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.liked_list, parent, false);
}
@Override
public void bindView(View view, final Context context, final Cursor cursor) {
imageViewStatus = (ImageView) view.findViewById(R.id.imageViewStatus);
textViewTitle = (TextView) view.findViewById(R.id.textViewTitle);
textViewDate = (TextView) view.findViewById(R.id.textViewTime);
idSpeaker = cursor.getInt(cursor.getColumnIndex("_id"));
///////////////delete item
imageViewStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.w("id",String.valueOf(idSpeaker));
mDatabaseHelper = new DatabaseHelper(context);
mSqLiteDatabase = mDatabaseHelper.getWritableDatabase();
mSqLiteDatabase.delete(mDatabaseHelper.TABLE_LIKED,
"liked_id = ?",
new String[] {String.valueOf(idSpeaker)});
cursor.requery();
notifyDataSetChanged();
}
});
但是,请始终删除 listView 中的最后一行。 (光标位置是最后一个)。
当我点击时,我不知道如何从 ListView 中获取当前位置。请帮助我
最佳答案
您正在bindView中初始化您的idSpeaker
,它总是为您提供数据的最后一个ID。因此,当您从表格中删除时,您的最后一项将被删除。
你只需要移动你的一行
idSpeaker=cursor.getInt(cursor.getColumnIndex("_id"));
从绑定(bind) View 到
imageViewStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cursor.moveToPosition(position);
idSpeaker = cursor.getInt(cursor.getColumnIndex("_id"));
Log.w("id",String.valueOf(idSpeaker));
mDatabaseHelper = new DatabaseHelper(context);
mSqLiteDatabase = mDatabaseHelper.getWritableDatabase();
mSqLiteDatabase.delete(mDatabaseHelper.TABLE_LIKED,
"liked_id = ?",
new String[] {String.valueOf(idSpeaker)});
cursor.requery();
notifyDataSetChanged();
}
});
关于android - 从 CursorAdapter 中的 ListView 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551144/