3

I have an uri in the form of a string and i need to correctly acquire the path from it. Since I have a function that will correctly remove the query parameters from an android.net.Uri object I was thinking of simply converting my string path to a uri.

Is Uri.parse a valid way of converting a string to a uri? I've looked at a few examples, but none really explained whether or not this was a valid approach or if any additional parsing would have to be done.

I have already looked at this link How to convert a String to an android.net.Uri but it didn't really answer my question.

Thanks for any advice!

Community
  • 1
  • 1
mna
  • 101
  • 1
  • 3
  • 7

1 Answers1

4

Yeah, you want to use Uri.parse(String). For example,

Uri uri = Uri.parse("content://com.example.provider.NotePad/notes/10");

To get the last segment, you would use

// id == "10"
String id = uri.getLastPathSegment();

To get the second to last segment, you would use

// notes == "notes"
String notes = uri.getPathSegments().get(0); 
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • I guess this is a silly question, but this will also handle http requests just fine? – mna Jun 22 '12 at 18:04
  • Well, `Uri.parse` parses a `Uri`. If you your HTTP requests are handled using the `URL` class, you won't be able to use `Uri.parse`. See this [**thread**](http://stackoverflow.com/q/1667278/844882) for more info. – Alex Lockwood Jun 22 '12 at 18:12
  • Maybe I'm mixing my terms. I'm new at this. I have a string (if I copy and paste what's inside the quotes into the browser it will download a file. So this string is "http://..blah.." that's what I meant by http requests.).I want to remove its query parameters by converting it to an Uri. Based on what I've read and your comments, it seems like Uri.parse would work but I wasn't sure. Does that clarify my orginal question at all? My other problem is that I don't understand the difference between an Url and an Uri. Wiki didn't make sense to me :( Thanks so much for the help! – mna Jun 25 '12 at 16:16
  • @user813375, A URL is a URI but a URI is not a URL. A URL is a specialization of URI that defines the network location of a specific representation for a given resource. A URI identifies a resource either by location or name. So basically the answer is **yes**, you can use `Uri.parse` on the string representation of a URL (but not the other way around). – Alex Lockwood Jun 25 '12 at 16:25
  • @user813375, {all `URL`s} is a subset of {all `URI`s} – Alex Lockwood Jun 25 '12 at 16:27
  • @user813375, this link may help you out: http://ajaxian.com/archives/uri-vs-url-whats-the-difference – Alex Lockwood Jun 25 '12 at 16:28
  • No problem! Remember to accept if you found it helpful :) http://i.stack.imgur.com/uqJeW.png Otherwise let me know if you have any other questions. – Alex Lockwood Jun 25 '12 at 18:40