DWA2112 DWA2112 - 1 year ago 67
Android Question

Deleting the last item in a list in Android

I am writing an Android simple To Do list app for learning purposes.

This is my function which updates the UI with the list items:

private void updateUI() {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK },//, TaskContract.Columns.DESCRIPTION},
null, null, null, null, null);

listAdapter = new SimpleCursorAdapter(
new String[]{TaskContract.Columns.TASK}, //TaskContract.Columns.DESCRIPTION },
new int[]{R.id.taskTextView},


I need an SQlite statement to delete the last item from the list. As I am new to Android, any help would be appreciated, thanks.

Answer Source

Deleting a row in Android is already covered in the SO question Deleting Row in SQLite in Android. Essentially, you use the delete() method on your SQLiteDatabase:

db.delete(tableName, whereClause, whereArgs);

So, as an example:

db.delete(TABLE_NAME, KEY_ID + "=?", new String[] { String.valueOf(keyIdOfRowToDelete) } );

The correct KEY_ID of the row you want to delete is on the last row of your cursor, accessible with the moveToLast() method:

int keyIdOfRowToDelete = cursor.getInt(cursor.getColumnIndex(KEY_ID_COLUMN_NAME));

After you have deleted the necessary entry, run another query(), as you have done in your question, to refresh the Cursor, and update your SimpleCursorAdapter by first calling swapCursor() with the new cursor, then notifyDataSetChanged():