How to add limit clause using content provider [duplicate]

走远了吗. 提交于 2019-11-27 22:12:51

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.

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") );

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!