之间的区别:getPathSegments().get(1) 和 / vs getLastPathSegment()
Difference between: getPathSegments().get(1) and / vs getLastPathSegment()
我看到两者都被用于在内容提供商中获取 ID。
String id = uri.getLastPathSegment();
String id = uri.getPathSegments().get(1);
有区别吗?如果是这样,一个比另一个更好/更好的做法吗?
或者在什么情况下你会使用一种而不是另一种?
Is there a difference?
只有恰好有 2 个路径段时它们才相同。对于 Uri
和 /a/path/that/looks/like/this/1
,get(1)
将不等于 getLastPathSegment()
。
and if so, is one better / better practice than the other?
使用有效的那个。在两者都起作用的情况下,使用更能表达您的意思的那个。而且,如果您不能决定,请掷硬币。
(FWIW,我会使用 getLastPathSegment()
,通常我的意思是 "get me the ID, which appears at the end of the Uri
")
我看到两者都被用于在内容提供商中获取 ID。
String id = uri.getLastPathSegment();
String id = uri.getPathSegments().get(1);
有区别吗?如果是这样,一个比另一个更好/更好的做法吗?
或者在什么情况下你会使用一种而不是另一种?
Is there a difference?
只有恰好有 2 个路径段时它们才相同。对于 Uri
和 /a/path/that/looks/like/this/1
,get(1)
将不等于 getLastPathSegment()
。
and if so, is one better / better practice than the other?
使用有效的那个。在两者都起作用的情况下,使用更能表达您的意思的那个。而且,如果您不能决定,请掷硬币。
(FWIW,我会使用 getLastPathSegment()
,通常我的意思是 "get me the ID, which appears at the end of the Uri
")