ContentURI之间的java差异。withAppendedId和Uri。buildon()。附录路径
我有点业余,正在上安卓在线课程。我发现这两个不同的代码片段要附加到URI
public static Uri buildWeatherUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
在这里,我得到了一个带有id附加到内容的URI
public static Uri buildWeatherLocation(String locationSetting) {
return CONTENT_URI.buildUpon().appendPath(locationSetting).build();
}
在这里,我得到一个带有locationSetting的URI,附加到内容\u URI
我想知道两者是否有相同的功能
# 1 楼答案
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,我们必须在使用appendPath(String newSegment)方法附加路径段后,使用withAppendedId(URI contentUri,long id)方法
Uri uri = Uri.parse("content://com.example.app").buildUpon() .appendPath("ExampleTable") .build()
Uri newUri = ContentUris.withAppendedId(uri, 2);
注意-
content
方案的Uri对象都很有用李>注意-
在将路径段附加到Uri对象之前,应该先对路径段进行编码,特别是如果我们计划使用-
URL url = new URL(Uri_to_string);
要在Uri对象(称为path)的末尾追加字符串,我们必须使用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)
# 2 楼答案
如果我们假设:
然后
现在让我们看看
ContentUris'
{a1}:区别在于使用这两种方法:
appendEncodedPath
vsappendPath
Encoding and Decoding URI Components
所以:
appendEncodedPath
appendPath