delete entry from sqlite data base in android appl

2019-09-03 15:46发布

问题:

After going through many posts I am posting my query. Not able to get proper resolution for my problem.

I am using sqlite and inserting some data (name, info etc..)

Now I get the all rows and show in list view.

Now user selects a one list entry for deletion, I have to call db.delete with id which is rowid of that particular record.

How will get the record id?

When user selects from list view I have position number which is index to the list. But not the database row id where that entry resides.

Do i have to save all ids returned when I call db.insert(table, data) when rows are created?

all examples show the implementation like

    public void deleteRow(long id) {

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

    }

where should i get id from?

回答1:

For setup a list view you have create an Adapter, right?

The adapter hold your entries and create the views.

Ask your adapter which item is on position x.

The BaseAdapter implement a getItemId method.

public long getItemId(int position) {

    // Example for List<Object>
    return mItems.get(position).getId();

}

You can simple call adapter.getItemId(x); or use OnItemClickListener that give the ID.

For more informations loot at the android developer pages.

SimpleAdapter: http://developer.android.com/reference/android/widget/SimpleAdapter.html

ArrayAdapter: http://developer.android.com/reference/android/widget/ArrayAdapter.html

BaseAdapter: http://developer.android.com/reference/android/widget/BaseAdapter.html

I hope it helps.

Updated:

Use getItemId(int) instead of getItem(int), thanks to @pskink