1

我正在为一个 android 应用程序创建一个内容提供程序,但是我在使用UriMatacher正确匹配 uri 时遇到了问题。

例如,我添加了 uri 来匹配(从链接中截取)

sURIMatcher.addURI("content://com.example", "people", PEOPLE);
sURIMatcher.addURI("content://com.example", "people/#", PEOPLE_ID);
sURIMatcher.addURI("content://com.example", "people/#/phones", PEOPLE_PHONES);

然后尝试访问contacts/people/1/phones. 成功的匹配最终是 withPEOPLE_ID而不是PEOPLE_PHONES

查询最初由此代码生成。

Uri uri = Uri.parse("content://com.example/people/#/phones");
ContentUris.appendId(uri.buildUpon(), 1).build();

在抛出一些日志语句后,我看到以下内容:

传递给查询的 uri给出了这个:

content://com.example/people/1#/phones

uri.getPath()给出了这个:

/people/1

uri 的第三个路径部分明显被删除,这就解释了为什么它匹配了错误的 uri。

来自 Android 开发者网站的示例似乎表明这不应该有问题。我是否错误地创建了uri?这只是一个错误吗?这是预期的功能吗(因此来自 android 开发人员的示例很糟糕)?

4

1 回答 1

3

Uri.parse()不知道 的UriMatcher通配符;这里,#是URI的片段标识符,所以当你解析时content://com.example/people/#/phones,它变成了content://com.example/people+片段/phones。id 正确地附加到 URI 的末尾,然后片段被结转。在这种情况下,您不能依赖ContentUris,而是需要长期构建 Uri:

                path = new Uri.Builder()
                .scheme( ContentResolver.SCHEME_CONTENT )
                .authority( DataProvider.AUTHORITY )
                .appendPath( "people" )
                .appendPath( "1" )
                .appendPath( "phones" ) ).build();
于 2013-02-14T06:13:05.440 回答