如何在Android中处理高级Uri模式

时间:2016-11-04 20:31:50

标签: android uri

使用复杂查询实现Content Provider需要复杂的uri模式,我不明白如何处理这个问题。

  1. 我可以在模式中使用正则表达式吗?例如:/user/:[a-zA-Z]/timeline/如果用户必须只包含字母。
  2. 哪些符号告诉UriMather参数示例:/user/:userId/timeline/year/:yearNumber,我会得到userId和yearNumber作为参数,那么我该如何获取值?我应该使用getPathSegments()并手动获取参数吗?
  3. 或者如果我使用/user/#/timeline/year/#我如何提取#values

1 个答案:

答案 0 :(得分:0)

使用格式/user/#/timeline/year/#,您可以致电:

uri.getPathSegments().get(1); // To get the first #
uri.getPathSegments().get(4); // to get the second #
// 0 -> user, 1 -> first #, 2 -> timeline, 3 -> year, 4 -> second #

因此,在您的内容提供商中,您将拥有以下内容:

private static final int USER_TIMELINE_YEAR = 1;
// ...

private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static
{
    uriMatcher.addURI(PROVIDER_NAME, "user/#/timeline/year/#", USER_TIMELINE_YEAR);
}

// Usually a ContentProvider method like query, insert, delete and update
public void someMethod(Uri uri) {
  if(uriMatcher.match(uri) == USER_TIMELINE_YEAR) {
      String userId = uri.getPathSegments().get(1);
      String timelineYear = uri.getPathSegments().get(4);
  }
}

检查https://developer.android.com/guide/topics/providers/content-provider-creating.htmlhttps://developer.android.com/reference/android/content/UriMatcher.html