How to remove a selected item from ListView using CursorAdapter

无人久伴 提交于 2019-11-28 08:41:49
viv

Try some thing like this :

@Override
public void bindView(View view, Context context, final Cursor cursor) {

    TextView txtName = (TextView) view.findViewById(R.id.txt_name);
    txtName.setText(cursor.getString(cursor.getColumnIndex(Helper
                                                           .tbl_col_username)));
    TextView txtPassword = (TextView) view.findViewById(R.id.txt_password);
    txtPassword.setText(cursor.getString(cursor.getColumnIndex(Helper
                                                           .tbl_col_password)));

    final String itemId = cursor.getString(cursor.getColumnIndex("id"));

    Button button = (Button) view.findViewById(R.id.btn_delete);
    button.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            Log.d(TAG, "Button Click ");
            deleteRecordWithId(itemId);
            cursor.requery();
            notifyDataSetChanged();
        }
    });
}

Im assuming this ID is in the cursor. Then simply make your own class DeleteEntryOnClicklistener which implements OnClickListener and let it take the ID in its constructor, and deletes the entry when clicked.

Please comment if I have misunderstood your problem or if Im being unclear, cheers :)

edit:

In your bindView(), change the OnClicklistener to something like this:

long id = cursor.getLong(cursor.getColumnIndex(Helper.tbl_col_id));
button.setOnClicklistener(new DeleteEntryOnClicklistener(id));

And DeleteEntryOnClicklistener should look something like this:

public class DeleteEntryOnClicklistener implements View.OnClickListener {

    long id;

    public DeleteEntryOnClicklistener(long id) {
        this.id = id;
    }

    @Override
    public void onClick(View v) {
        database.deleteEntry(id);
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!