我有点业余,做我的Android在线课程。我发现这两个不同的代码片段附加到URI
public static Uri buildWeatherUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
我在这里获得了 CONTENT_URI
附加了 id 的URIpublic static Uri buildWeatherLocation(String locationSetting) {
return CONTENT_URI.buildUpon().appendPath(locationSetting).build();
}
我在这里获得了一个 CONTENT_URI 附加 locationSetting 的URI
我想知道两者是否具有相同的功能?
答案 0 :(得分:2)
如果我们假设:
CONTENT_URI = content://com.example.myapp
然后
buildWeatherUri(5) -> content://com.example.myapp/5
buildWeatherLocation("location") -> content://com.example.myapp/location
现在让我们看ContentUris'
source code:
public class ContentUris {
public static long parseId(Uri contentUri) {
String last = contentUri.getLastPathSegment();
return last == null ? -1 : Long.parseLong(last);
}
public static Uri.Builder appendId(Uri.Builder builder, long id) {
return builder.appendEncodedPath(String.valueOf(id));
}
public static Uri withAppendedId(Uri contentUri, long id) {
return appendId(contentUri.buildUpon(), id).build();
}
}
区别在于使用这两种方法:
appendEncodedPath
vs appendPath
Encoding and Decoding URI Components
URI的每个组件都允许一组有限的合法字符。 必须先对其他字符进行编码,然后才能嵌入其中 一个URI。要从URI恢复原始字符,它们可能是 解码。
所以:
将给定的段追加到路径中。
对给定的段进行编码并将其附加到路径中。
答案 1 :(得分:2)
appendPath(String newSegment)对给定的路径段进行编码,并将其附加到Uri对象的末尾。
withAppendedId(Uri contentUri,long id)只是将给定的Id附加到给定的Uri对象的末尾,而不对其进行编码。
示例强> -
查看此URI http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22
由于它是一个URL,我们必须使用 appendPath(String newSegment)和appendQueryParameter(String key,String value)方法创建它,因为它们都首先对参数进行编码在附加它们之前传递给它们。
Uri.parse("http://samples.openweathermap.org").buildUpon()
.appendPath("data")
.appendPath("2.5")
.appendPath("weather")
.appendQueryParameter("q", "London")
.appendQueryParameter("appid", "b6907d289e10d714a6e88b30761fae22")
.build();
查看内容提供商的此URI content://com.example.app/ExampleTable/2
。
由于它在末尾包含一个数字,指向一个表项,因此要创建这样的URI,我们必须在追加后使用 withAppendedId(Uri contentUri,long id)方法使用 appendPath(String newSegment)方法
的路径段 Uri uri = Uri.parse("content://com.example.app").buildUpon()
.appendPath("ExampleTable")
.build()
Uri newUri = ContentUris.withAppendedId(uri, 2);
请注意 -
content
方案的Uri对象都很有用。注意强> -
路径段的编码应该在将它附加到Uri对象之前完成,如果我们计划使用以下方法构建一个URL:
URL url = new URL(Uri_to_string);
要在Uri对象的末尾附加字符串,称为路径,我们必须使用 appendPath(String newSegment)方法。
探索更多 -
https://developer.android.com/reference/android/net/Uri.Builder.html (Uri.Builder |官方文档)
https://developer.android.com/reference/android/content/ContentUris.html (ContentUris |官方文档)
Why do you need to encode URLs? (为什么需要编码URL?| StackOverFlow)