Explain Codes LogoExplain Codes Logo

Parsing query strings on Android

java
url-parsing
query-string
android-development
Anton ShumikhinbyAnton Shumikhin·Dec 2, 2024
TLDR

Get the value from a query string in Android, swiftly and professionally, using Uri:

Uri uri = Uri.parse("http://example.com/?key=value"); String value = uri.getQueryParameter("key"); // returns "value", no not "The Last Jedi"

Make use of Uri.parse() to conveniently handle the URL and use getQueryParameter() to extract your coveted value from your query. One-shot, spot-on solution for retrieving data from URL queries.

Multiple birds, one stone

Need to extract multiple values for the same query parameter? A simple iteration through the query parameter set solves it:

Set<String> keys = uri.getQueryParameters("key"); for (String key : keys) { // Process each value of "key", clone the keys if you are feeling like a locksmith. 😉 }

Bypassing native Uri limitations

Even though Uri.getQueryParameter() is pretty nifty, there's a bug in versions below Android M, causing it to return only the last value for repeated parameter names. Hence, if you're developing for such versions, you might have to get your hands dirty with manual parsing.

Alternative: UrlQuerySanitizer

If you need a more flexible query string parsing, use UrlQuerySanitizer:

UrlQuerySanitizer sanitizer = new UrlQuerySanitizer("http://example.com/?key=value&key=value2"); String aValue = sanitizer.getValue("key"); // returns both "value" and "value2", variety is the spice of life right?

UrlQuerySanitizer allows for fine-tuning of query string parsing, even specifying legal and illegal parameters. For dynamic query string handling, use getAllButNullLegal().

Leverage external libraries

For more extensive functionality, consider using Jetty's util classes or Apache's URLEncodedUtils. However, Apache's library's deprecated status on newer Android versions might be a deal breaker for some. With ready-to-use methods like UrlEncoded.decodeTo(), parsing has never been easier.

The manual way: custom parsing

If you fancy a DIY approach, here are some best practices:

  • Remind yourself to split the URL to isolate the query part.
  • Use URLDecoder to decode the keys and values, it doesn't just decode secret messages.
  • Remember to store key-value pairs in a Map for easy access.
  • Make sure you cater for UnsupportedEncodingException — an exception that's more complicated than it sounds.

By now, you know your way around parsing query strings. Let's learn how to avoid some common stumbling blocks:

  • Not decoding URL-encoded parameters: Keep it encoded and you might find a whole new language.
  • Failing to consider multiple parameters with the same name: Double trouble isn't just a movie!
  • Overlooking null and empty parameters: They represent more than just an existential crisis.
  • Ignoring backward compatibility: Beware, the past does come back to haunt sometimes!

The right parsing tool for the job

Approach the parsing tool selection process as you would any major life decision:

  • Take the API level you’re targeting into account.
  • Check if you need to handle repeated parameter names.
  • Balance the flexibility of custom solutions and the reliability of library methods. It's like choosing between hiking boots and running shoes—both get the job done, but in different terrains.
  • Evaluate the time and effort factor—do you want quick and reliable or custom and flexible?