DWA
DWA

Reputation: 530

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(
                this,
                R.layout.task_view,
                cursor,
                new String[]{TaskContract.Columns.TASK}, //TaskContract.Columns.DESCRIPTION },
                new int[]{R.id.taskTextView},
                0
        );

        this.setListAdapter(listAdapter);
    }

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.

Upvotes: 0

Views: 326

Answers (2)

user5395084
user5395084

Reputation:

First, you need to count the items of the list, using something like count or length, then get the item by index (get the index with counted items) and delete it

Upvotes: 1

PPartisan
PPartisan

Reputation: 8231

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:

cursor.moveToLast();
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():

listAdapter.swapCursor(newCursor);
listAdapter.notifyDataSetChanged();

Upvotes: 1

Related Questions