【问题标题】:How to add limit clause using content provider [duplicate]如何使用内容提供者添加限制条款[重复]
【发布时间】:2012-04-11 11:40:27
【问题描述】:

有没有办法限制内容提供者返回的行数? 我找到了这个solution,但是,它对我不起作用。仍在返回所有行。

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

【问题讨论】:

  • 只是一个想法。但是您可以尝试将限制子句作为最后一个参数。像这样 activity.managedQuery(playlistUri, null, null, null, "limit 3") ?

标签: android uri limit android-contentprovider


【解决方案1】:

我遇到了这个问题并且不得不打破我的头,直到我终于弄明白了,或者更确切地说,我找到了一个对我有用的方法。试试下面的

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

最后一个参数用于 sortOrder。我提供了排序顺序,并将 LIMIT 附加到它上面。确保正确分配空间。我必须检查正在形成的查询,这似乎有效。

【讨论】:

  • “ASC LIMIT 2”会不起作用吗?
  • 如果需要按 asc 顺序排列的最后 2 行,则将不起作用。它将获取前两行
  • 更好的方法见here
【解决方案2】:

很遗憾,ContentResolver 无法查询有限制参数。在您的 ContentProvider 中,您的 MySQLQueryBuilder 可以查询添加额外的限制参数。

按照议程,我们可以在 ContentProvider 中添加额外的 URI 规则。

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

然后在你的查询方法中

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

从 Activity 中查询 ContentProvider。

 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】:

    一般原则上,内容提供者应注意限制参数。 不幸的是,它并没有被普遍实施。

    例如,在编写内容提供程序来处理 SearchManager 查询时:

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

    在没有实现的地方,你只能求助于在排序子句上粘贴限制的丑陋选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多