26

I am able to find how to convert android.net.Uri to Java.net.URI here but not vice-versa.

So after spending some time I figured it out. Here is the solution(If there is another solution then please post that as well)

First convert javaURI to string and then use android.net.Uri's parse function

android.net.URI androidUri = android.net.Uri.parse(javaURI.toString());
1

3 Answers 3

33

http://developer.android.com/reference/android/net/Uri.html#parse(java.lang.String)

public static Uri parse (String uriString)

Creates a Uri which parses the given encoded URI string.

Parameters
uriString: an RFC 2396-compliant, encoded URI

Returns
Uri for this given uri string

Throws
NullPointerException if uriString is null


Therefore, here is an example:

android.net.Uri.parse(new java.net.URI("").toString());

Goes without saying, use the real java.net.URI in it... ;)

1
  • 1
    This also means you can run Unit Tests on the local JVM without worrying about the Android SDK being present therefore making life a lot easier. Commented May 5, 2016 at 14:52
4

For anyone coming across this, I had success with the following code:

URI oldUri;
Uri newUri  = new Uri.Builder().scheme(oldUri.getScheme())
                    .encodedAuthority(oldUri.getRawAuthority())
                    .encodedPath(oldUri.getRawPath())
                    .query(oldUri.getRawQuery())
                    .fragment(oldUri.getRawFragment())
                    .build();

Basically, get each URI component and pass it to the builder (as there does not seem to be a way to pass in a whole URI string.

5
  • 8
    310 characters vs 43 characters... - Uri newUri = Uri.parse(oldUri.toString()); - hmm...
    – user1974640
    Commented Mar 11, 2014 at 13:29
  • Just brilliant @saleemrashid1
    – user3746280
    Commented Jul 9, 2014 at 15:22
  • Why in the name of god would you do something like that? Commented Oct 17, 2018 at 18:54
  • 1
    Downvoted because android.net.Uri already have a parse method
    – GabrielBB
    Commented Dec 2, 2018 at 13:05
  • Thank you for this solution. You may want to add a line to handle URIs that contain port numbers.
    – George
    Commented Jul 29, 2021 at 0:13
1
uri = Uri.parse(mFile.toString());

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.