Convert String to Uri
How can I convert a String to a Uri in Java (Android)? i.e.:
String myUrl = "http://stackoverflow.com";
myUri = ???;
You can use the parse
static method from Uri
//...
import android.net.Uri;
//...
Uri myUri = Uri.parse("http://stackoverflow.com")
I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
You can parse a String to a Uri by using Uri.parse() as shown below:
Uri myUri = Uri.parse("http://stackoverflow.com");
The following is an example of how you can use your newly created Uri in an implicit intent. To be viewed in a browser on the users phone.
// Creates a new Implicit Intent, passing in our Uri as the second paramater.
Intent webIntent = new Intent(Intent.ACTION_VIEW, myUri);
// Checks to see if there is an Activity capable of handling the intent
if (webIntent.resolveActivity(getPackageManager()) != null){
startActivity(webIntent);
}
NB: There is a difference between Androids URI and Uri.