如何获取内容提供商中的 _count?
我应该怎么做才能让我的内容提供商返回包含记录数的 _count 列? 文档说它是自动的,但也许它只需要一些内置的内容提供程序。 对数据库运行查询似乎不会返回它。
What should I do to get my content provider to return the _count column with the count of records? The documentation says it is automatic, but maybe it's only taking about some built-in content provider. Running a query to the database seems not to return it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 contentProvider,那么您必须像
count(*) AS count
那样执行。如果您使用cursor.getCount(),则效率不如上述方法。 使用cursor.getCount(),您可以获取所有记录以获取计数。 整个代码应该如下所示 -
之所以有效,是因为 android 需要定义一个列名。
If you are using contentProvider then you have to do it like
count(*) AS count
.If you use
cursor.getCount()
, that would not be as efficient as the above approach. Withcursor.getCount()
you are fetching all the records just to get counts. The entire code should look like following -The reason why this works is because android needs a column name to be defined.
如果您使用
ContentProvider.query()
,则会返回Cursor
。 调用 Cursor.getCount() 来获取返回游标中的记录计数。If you are using
ContentProvider.query()
aCursor
is returned. CallCursor.getCount()
to get a count of records in the returned cursor.我遇到了类似的问题,发现这对我有用。 在下面的示例中,我想从 MediaStore 提供商获取图像的数量。
I had a similiar problem and found this worked for me. In the example below I wanted to get the count of images from the MediaStore provider.
使用
cursor.getCount()
,您无法确保它返回所返回项目的真实数量。 还有很多更好的方法:1- 如果您使用内容提供程序,则可以执行查询并使用 BaseColumns 中包含的
列 (_COUNT)
进行投影2- 使用
执行 rawQuery SELECT COUNT(*)
正如 @saurabh 在他的回复中所说。With
cursor.getCount()
you can not assure that it returns the real number of items returned. There are much better ways:1- If you are using Content Providers, you can do a query and use the
Column (_COUNT)
included in BaseColumns for your projection2- To do a rawQuery using
SELECT COUNT(*)
as @saurabh says in his response.