How to add limit clause using content provider [du

2019-01-14 16:56发布

问题:

This question already has an answer here:

  • Specifying limit / offset for ContentProvider queries 4 answers

Is there a way to limit the number of rows returned from content provider? I found this solution, however, it did not work for me. All of the rows are still being returned.

Uri uri = Playlists.createIdUri(playlistId); //generates URI
uri = uri.buildUpon().appendQueryParameter("limit", "3").build();     
Cursor cursor = activity.managedQuery(playlistUri, null, null, null, null);

回答1:

I have had this issue and had to break my head till I finally figured it out, or rather got a whay that worked for me. Try the following

Cursor cursor = activity.managedQuery(playlistUri, null, null, null, " ASC "+" LIMIT 2");

The last parameter is for sortOrder. I provided the sort order and also appended the LIMIT to it. Make sure you give the spaces properly. I had to check the query that was being formed and this seemed to work.



回答2:

Unfortunately, ContentResolver can't query having limit argument. Inside your ContentProvider, your MySQLQueryBuilder can query adding the additional limit parameter.

Following the agenda, we can add an additional URI rule inside ContentProvider.

static final int ELEMENTS_LIMIT = 5;
public static final UriMatcher uriMatcher;

static {
uriMatcher = new UriMatcher( UriMatcher.NO_MATCH );
........
uriMatcher.addURI(AUTHORITY, "elements/limit/#", ELEMENTS_LIMIT);
}

Then in your query method

String limit = null; //default....
    switch( uriMatcher.match(uri)){
       .......
                case ELEMENTS_LIMIT:
                    limit = uri.getPathSegments().get(2);
                break;
       ......

            }

return mySQLBuilder.query( db, projection, selection, selectionArgs, null, null, sortOrder, limit );

Querying ContentProvider from Activity.

 uri = Uri.parse("content://" + ContentProvider.AUTHORITY + "/elements/limit/" + 1 );

//In My case I want to sort and get the greatest value in an X column. So having the column sorted and limiting to 1 works.
    Cursor query = resolver.query(uri,
                        new String[]{YOUR_COLUMNS},
                        null,
                        null,
                        (X_COLUMN + " desc") );


回答3:

A content provider should on general principle pay attention to a limit parameter. Unfortunately, it is not universally implemented.

For instance, when writing a content provider to handle SearchManager queries:

String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);

Where it isn't implemented you can only fall back on the ugly option of gluing a limit on the sort clause.