Java ContentUris.withAppendedId和Uri.Buildon().appendPath之间的差异

Java ContentUris.withAppendedId和Uri.Buildon().appendPath之间的差异,java,android,uri,Java,Android,Uri,我有点业余,正在上安卓在线课程。我发现这两个不同的代码片段要附加到URI public static Uri buildWeatherUri(long id) { return ContentUris.withAppendedId(CONTENT_URI, id); } 在这里,我得到了一个带有id附加到内容的URI public static Uri buildWeatherLocation(String locationSetting) { return CONTE

我有点业余,正在上安卓在线课程。我发现这两个不同的代码片段要附加到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

public static Uri buildWeatherLocation(String locationSetting) {
     return CONTENT_URI.buildUpon().appendPath(locationSetting).build();
 }
我想知道两者是否有相同的功能

如果我们假设:

CONTENT_URI = content://com.example.myapp
然后

现在让我们看看
ContentUris'

区别在于使用这两种方法:

appendEncodedPath
vs
appendPath

URI的每个组件都允许一组有限的合法字符。 必须先对其他字符进行编码,然后才能将其嵌入 URI。要从URI恢复原始字符,可以 解码

因此:

将给定段追加到路径

对给定段进行编码并将其附加到路径

appendPath(String newSegment)对给定的路径段进行编码,并将其附加到Uri对象的末尾

withAppendedId(Uri contentUri,long id)只需将给定id附加到给定Uri对象的末尾,而不进行编码

示例-

  • 看看这个URI
    http://samples.openweathermap.org/data/2.5/weather?q=London,英国和appid=b6907d289e10d714a6e88b30761fae22

  • 由于它是一个URL,我们必须使用appendPath(String newSegment)和appendQueryParameter(String key,String value)方法创建它,因为这两种方法在追加参数之前都首先对传递给它们的参数进行编码

    Uri.parse(“http://samples.openweathermap.org).buildon()
    .appendPath(“数据”)
    .appendPath(“2.5”)
    .appendPath(“天气”)
    附录q参数(“q”、“伦敦”)
    附录参数(“附录ID”,“b6907d289e10d714a6e88b30761fae22”)
    .build()

  • 看看这个URI
    content://com.example.app/ExampleTable/2
    用于内容提供商

  • 由于它在末尾包含一个数字,指向单个表项,因此要创建这样的URI,我们必须在使用appendPath(String newSegment)方法附加路径段后,使用withAppendedId(URI contentUri,long id)方法

    Uri=Uri.parse(“content://com.example.app).buildon()
    .appendPath(“示例”)
    .build()

    urinewuri=ContentUris.withAppendedId(Uri,2)

请注意-

  • 在Uri.Builder类中定义的所有方法对于构建Uri对象都很有用
  • ContentURI类中定义的所有方法对于使用
    content
    方案的Uri对象都很有用
注意-

  • 在将路径段附加到Uri对象之前,应该先对路径段进行编码,特别是当我们计划使用-
    URL URL=新的URL(Uri到字符串)

  • 要在Uri对象的末尾追加字符串,称为path,我们必须使用appendPath(stringnewsegment)方法

探索更多信息-

  • (Uri.Builder |官方文件)

  • (ContentUris |官方文件)

  • (为什么需要对URL进行编码?| StackOverFlow)

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