问题
I'm just starting to dive into some basic Android development and have been experimenting with a ListView
and integrating it with a SimpleCursorAdapter
. I look through a lot of online code samples, but I also have a book to use as a reference (Professional Android 2 Application Development).
In the book they work out an example To-Do list application that stores the list items in a SQLite database with an auto-incrementing, integer, primary key field.
A user can create new list items, but can also delete a selected item from the list. In the code, when the delete occurs, the primary key field is restricted (within the WHERE
clause of the SQL statement) by the position
attribute of the item as opposed to the item's rowid
.
To me, this seems like an incorrect implementation. Looking at the SQLite documentation for AUTOINCREMENT
, it says that this value will always increase and old values will never be re-used on the same table. So if you're deleting and adding things to the list, it would seem that the position and row id can get out of sync rather quickly.
Am I correct, then, to assume that the row id is the correct way to "index" into the database table and not the list position? I think the position would be safe to use if one is using the regular ListAdapter
, but doesn't seem suitable when indexing into the database.
回答1:
That is definitely bad practice. I always use the row id to delete, and use the position id to retrieve the cursor's row id. I have the first edition of that book at home, I'm going to take a look at it myself later.
回答2:
You can use the position to get a cursor to a particular list entry (and this cursor would be the 'row' in the 'table' corresponding to the row id):
Cursor cursor = (Cursor)parent.getItemAtPosition(pos);
int rowCol = c.getColumnIndex("_id");
Then you should see that cursor.getLong(rowCol) == id
来源:https://stackoverflow.com/questions/6658115/listview-row-id-and-position-index-confusion