Delete item from ListView on Long press -Cursor Adapter – Android

DBHelper db;
Cursor c;
RecordCursorAdapter recordCursorAdapter;
// RecordCursorAdapter extends CursorAdapter class

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView arg0, View v, int position, long arg3) {
                AlertDialog.Builder ad = new AlertDialog.Builder(ListActivity.this);
                ad.setTitle("Delete");
                ad.setMessage("Sure you want to delete record ?");
                final int pos = position;
                ad.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Delete of record from Database and List view.
                        c.moveToPosition(pos);
                        db.delete(c.getInt(c.getColumnIndex(DBHelper.KEY_ID)));
                        c=db.getAll();
                        recordCursorAdapter.swapCursor(c);
                        listView.setAdapter(recordCursorAdapter);
                    }
                });
                ad.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                ad.show();
                return false;
            }
        });


Delete and getAll() function in DBHelper class

    public void delete(int anInt) {
        SQLiteDatabase db = this.getWritableDatabase();

        db.delete(TABLE_RECORD,KEY_ID+"=?",new String[]{String.valueOf(anInt)});
        db.close();
    }

public Cursor getAll(){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery("SELECT  * FROM "+TABLE_RECORD, null);
        return c;
    }

One thought on “Delete item from ListView on Long press -Cursor Adapter – Android”

Leave a Reply

Your email address will not be published. Required fields are marked *