Search code examples
androidpathuriandroid-contentprovider

Difference between: getPathSegments().get(1) and / vs getLastPathSegment()


I've seen both being used for getting the ID in a content provider.

String id = uri.getLastPathSegment();
String id = uri.getPathSegments().get(1);

Is there a difference? and if so, is one better / better practice than the other?

Or in which situation would you use one and not the other?


Solution

  • Is there a difference?

    They are only the same if there are exactly 2 path segments. For a Uri with /a/path/that/looks/like/this/1, get(1) will not equal getLastPathSegment().

    and if so, is one better / better practice than the other?

    Use the one that works. In the situation where both work, use whichever one expresses your meaning better. And, if you can't decide, flip a coin.

    (FWIW, I would use getLastPathSegment(), as usually my meaning is "get me the ID, which appears at the end of the Uri")