ListView行id和位置索引混淆
我刚刚开始深入研究一些基本的 Android 开发,并一直在尝试使用 ListView
并将其与 SimpleCursorAdapter
集成。我浏览了很多在线代码示例,但我还有一本书可以用作参考(专业Android 2应用程序开发)。
在书中,他们设计了一个示例待办事项列表应用程序,该应用程序将列表项存储在具有自动递增整数主键字段的 SQLite 数据库中。
用户可以创建新的列表项,但也可以从列表中删除选定的项目。在代码中,当删除发生时,主键字段受到项目的 position
属性的限制(在 SQL 语句的 WHERE
子句中),而不是项目的rowid
。
对我来说,这似乎是一个不正确的实现。查看AUTOINCRMENT
的SQLite文档,它说这个值将始终增加,并且旧值永远不会在同一个表上重复使用。因此,如果您在列表中删除和添加内容,位置和行 ID 似乎很快就会不同步。
那么,我是否正确地假设行 id 是“索引”到数据库表而不是列表位置的正确方法?我认为如果使用常规 ListAdapter
,该位置可以安全使用,但在索引到数据库时似乎不合适。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用该位置将光标获取到特定列表条目(该光标将是“表”中与行 id 对应的“行”):
然后您应该看到
cursor.getLong(rowCol) == ID
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):
Then you should see that
cursor.getLong(rowCol) == id
这绝对是不好的做法。我总是使用行id来删除,并使用位置id来检索光标的行id。我家里有那本书的第一版,以后我自己也看一下。
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.