Search code examples
androidandroid-contentprovider

Android SearchRecentSuggestionsProvider query limit


I'm working with search suggestion framework and here is the case. I get some query string and make query from content resolver, but problem is that I can't limit the results. Found several solutions but they dont work for me.

My content provider is extending SearchRecentSuggestionsProvider and declared in manifest, here query uri Uri URI = Uri.parse("content://" + AUTHORITY + "/search_suggest_query");

sol 1: adding query parameter to uri

SearchSuggestionProvider.URI.buildUpon().appendQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT, String.valueOf(5)).build()

sol 2: adding limit in sortOrder query parameter

getContentResolver().query(URI, null, "?", new String[]{searchQuery}, "_id asc limit 5");

In both cases query returns all rows from search suggestions. Does anyone know how to limit such a query?


Solution

  • Below is the query method in the base class SearchRecentSuggestionsProvider in the framework

    /**
         * This method is provided for use by the ContentResolver.  Do not override, or directly
         * call from your own code.
         */
        // TODO: Confirm no injection attacks here, or rewrite.
        @Override
        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, 
                String sortOrder) {
    

    Potentially you can override it and implement the limiting - but as you can see the comment above it clear states "do not override". In the existing method no limiting is enforced.

    However I see in some of the other answers on stack-overflow and other sites that people do override it.

    Example : Use SearchRecentSuggestionsProvider with some predefined terms?

    Based on this I think you can try it out - override the query method and add your own implementation which supports limiting the results. Parse the SearchManager.SUGGEST_PARAMETER_LIMIT that you have used in the query method and use it to limit the results returned.