Android:通过 ContentValues 增加 DB 字段
我正在通过 getContentResolver().update() 方法更新 ListView 中的项目,并且我想通过 ContentValue 增加“视图”字段,但无法弄清楚是否这是可能的。
我可以使用原始 SQL SETviews=views+1
来完成此操作,但设置一个 ContentValue,例如 cv.put("views", "views + 1")
结果在视图字段中明确设置为“视图+1”而不是数字。
有任何关于此的指示吗,还是我只能采用更手动的方法?
谢谢,
Paul
更新:
我现在已经回到使用原始 SQL 来执行更新,然后通过 getContentResolver().notifyChange()
手动通知底层 CursorAdapter 的更改。如果我能找到一种直接通过 getContentResolver().update() 来完成此操作的方法,那就太好了,所以如果有人有办法做到这一点,请在此处发布。
I'm updating an item in a ListView via the getContentResolver().update()
method, and I'd like to increment a 'views' field via a ContentValue, but can't figure out if this is possible.
I could do this with raw SQL SET views = views + 1
, but setting a ContentValue, such as cv.put("views", "views + 1")
results in the views field being set explicitly to "views + 1" rather than a number.
Any pointers on this on, or am I left to a more manual approach?
Thanks,
Paul
UPDATE:
I've gone back to using raw SQL to perform the update for now, and then manually notify the underlying CursorAdapter of the change via getContentResolver().notifyChange()
. Would still be great if I could figure out a way to do this directly via getContentResolver().update()
, so if anyone has a way to do that, please post it here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的最终解决方案是通过
ContentProvider
使用自定义Uri
(沿着...item/5/updateviews
的行),例如调用getContentResolver().update(customUri, ...)
并传递此Uri
告诉我的 ContentProvider 的重写update()
方法以递增该项目的查看次数,从而避免需要通过其ContentValues
参数将值传递给update()
。My final solution to this was to use a custom
Uri
(along the lines of...item/5/updateviews
) via theContentProvider
such that a call togetContentResolver().update(customUri, ...)
passing thisUri
tells my ContentProvider's overriddenupdate()
method to increment the view count for this item, thus avoiding the need to pass values toupdate()
via it'sContentValues
parameter.我在内容提供程序上实现了调用 API,作为将原始/一次性 SQL 查询直接发送到底层 SQLiteDatabase 的一种方式。这很容易。
I implemented the call API on my content provider as a way of sending raw/one-off SQL queries directly to the underlying SQLiteDatabase. It was easy enough.
与使用 ContentValues 类似的东西。
一个可能更简单的路线可能是:
database.execSQL("UPDATE my_table_name SET my_counter_field = my_counter_field + 1 WHERE my_where_field = ?", new Object[] {key});
或者甚至可以使用触发器。请参阅此问题,看看它是否适合您的需求:使用触发器进行自动增量
something like that for using
ContentValues
.a possibly simpler route may be:
database.execSQL("UPDATE my_table_name SET my_counter_field = my_counter_field + 1 WHERE my_where_field = ?", new Object[] {key});
or maybe even use a Trigger. See this question to see if it suites your needs: Use trigger for auto-increment