Explain Codes LogoExplain Codes Logo

Convert String to Uri

java
uri
android
error-handling
Nikita BarsukovbyNikita Barsukov·Aug 8, 2024
TLDR

Take a String and convert it to a Uri using Uri.parse():

Uri uri = Uri.parse("http://www.example.com");

Your URL String "http://www.example.com" magically transforms into a Uri object, ideal for your Android Intents or any web functionalities.

The internals in plain English

The Uri.parse() method is a hardworking agent, doing the bulk of work. It validates the input string, creates a Uri instance that Android could understand, allowing you to simplify URI parsing and ensure proper syntax and encoding.

Covering your bases with Java and Android

If you cross borders and switch between Android and Java ecosystems, keep in mind the differences. Java has its java.net.URI, a class for URI conversion that works across all Java applications, not just Android:

URI javaUri = URI.create("http://www.example.com"); // or alternatively URI javaUri = new URI("http://www.example.com");

Kotlin's trick shot

With Kotlin, and the Android KTX library, you get an additional trick shot - the toUri() extension function:

import androidx.core.net.toUri val kotlinUri = "http://www.example.com".toUri()

Don't forget that extension functions like toUri() depends on androidx.core:core-ktx being part of your project dependencies.

Knowing your URI classes: Android vs. Java

There are significant differences between android.net.Uri and java.net.URI. Always choose wisely depending on your project:

  • For Android-specific projects, stick to android.net.Uri for native capabilities and interoperability across Android components.
  • For non-Android Java applications, java.net.URI is your go-to class, for broad compatibility across Java-based platforms.

Uri parsing: error handling to the rescue

When dealing with Uri parsing, be prepared for runtime exceptions if the supplied string isn't a valid Uri. A try-catch block is like a superhero cape for your code:

try { Uri uri = Uri.parse("http://www.example.com"); // If Batman was a programmer, he'd love try-catch. Just saving codes from exceptions! } catch (IllegalArgumentException e) { // Handle the exception in true Batman style! }

Context matters: Handling Implicit Intents

In the Android multiverse, not every activity can handle every type of Uri. When working with implicit intents, double-check if an activity can handle the Uri:

Intent intent = new Intent(Intent.ACTION_VIEW, uri); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } // It's like asking, "Does anyone know how to handle this?" If yes, you go for it!

Avoiding an ActivityNotFoundException—sort of like avoiding traffic on your way home—improves the user experience by making sure your app functions just like it's supposed to.