ListView行id和位置索引混淆

发布于 2024-11-19 16:34:55 字数 606 浏览 5 评论 0原文

我刚刚开始深入研究一些基本的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山色无中 2024-11-26 16:34:55

您可以使用该位置将光标获取到特定列表条目(该光标将是“表”中与行 id 对应的“行”):

Cursor cursor = (Cursor)parent.getItemAtPosition(pos);
int rowCol = c.getColumnIndex("_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):

Cursor cursor = (Cursor)parent.getItemAtPosition(pos);
int rowCol = c.getColumnIndex("_id");

Then you should see that cursor.getLong(rowCol) == id

时光倒影 2024-11-26 16:34:55

这绝对是不好的做法。我总是使用行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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文