优化 Android 中现有搜索查询的结果
在我的 Android 应用程序中,我想对内容提供程序执行查询,然后优化该搜索(我有两个 WHERE
子句字符串)。第二个查询应返回的记录是第一个查询返回的行的子集。
我当前的解决方案是这样的:
Cursor cursor1 = query (myUri, myProjection, where1, null, null);
//do stuff
Cursor cursor2 = query (myUri, myProjection, where2, null, null);
//do other stuff
如果我这样做,第二次查询运行根本就不是很有效(它搜索整个数据库,就像第一次一样)。我希望第二个查询仅针对cursor1 中返回的行运行。这可以做到吗?如何做到?
android 文档指出,如果我使用具有不同参数的相同(参数化)where 字符串,则查询可能会被缓存。这有用吗,或者有完全不同的方法吗?
In my Android app, I want to execute a query against a content provider, and then refine that search (I have two WHERE
clause strings). The records that should be returned by the second query are a subset of the rows returned by the first query.
My current solution is like this:
Cursor cursor1 = query (myUri, myProjection, where1, null, null);
//do stuff
Cursor cursor2 = query (myUri, myProjection, where2, null, null);
//do other stuff
If I do this, the second query run is not very efficient at all (it searches the full database, just like the first). I would like the second query to run only against the rows that are returned in cursor1. Can this be done, and how?
The android documentation states that queries may be cached if I use the same (parameterised) where string, with different parameters. Could this be useful, or is there a totally different way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查 CursorAdapter。它实现了 Filterable 接口,并包含一些有趣的方法:setFilterQueryProvider 和 getFilterQueryProvider。我没有使用过 CursorAdapter,但如果它与其他适配器(或实现 Filterable 的自定义适配器)类似,那么它正是您所需要的。
更新这是一个示例:http://www.outofwhatbox.com/blog/2010/11/android-simpler-autocompletetextview-with-simplecursoradapter/
你的部分感兴趣的是:
当它返回新的 Cursor 实例时,我假设它确实再次命中数据库。您可以通过迭代游标并查找匹配来实现自己的搜索逻辑。您将必须编写一些基准测试,看看是否值得避免使用新查询来访问数据库,因为通过手动迭代游标,您将更难访问数据库。请记住,除非您明确要求(通过在游标上调用任何 readXXX() ),否则您实际上并没有从数据库检索数据(行/记录)。
顺便说一句,您可能对 ORMLite 感兴趣
Check CursorAdapter. It implements Filterable interface and contains a few interesting methods: setFilterQueryProvider and getFilterQueryProvider. I haven't used CursorAdapter, but if it is similar to other adapters (or custom adapters implementing Filterable) then it is exactly what you need.
UPDATE Here is an example: http://www.outofwhatbox.com/blog/2010/11/android-simpler-autocompletetextview-with-simplecursoradapter/
The part you are interested in is this:
As it returns new Cursor instance I assume that it does hit DB one more time. You might implement your own search logic by iterating cursor and looking for matches. You will have to write some benchmark to see if it is worth avoiding hitting database with a new Query as by manually iterating Cursor you will be hitting database harder. Remember that you do not actually retrieve data (row/record) from DB unless you explicitly ask for it (by calling any of the readXXX() on a Cursor).
BTW you might be interested in ORMLite