Parsing query strings on Android
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
On Android, query strings commonly appear in deep links, browser callbacks, and OAuth redirects. The safest default is to let the platform parse them through Uri, because manual string splitting tends to break on encoding, repeated keys, and malformed input.
Use Uri for Normal URLs and Deep Links
When you receive a full URL, parse it once and read its parameters through Uri methods.
This is clearer and more robust than splitting on & and = yourself.
Handle Repeated Parameters Intentionally
Some URLs legitimately contain the same key more than once. Analytics tags, filters, and search parameters often do this. If you call getQueryParameter, Android returns only one value. Use getQueryParameters when repetition matters.
If your app expects multiple values, model that requirement directly instead of silently throwing the extras away.
Parse Raw Query Text Only When Necessary
Sometimes you receive only the query fragment, not a full URL. In that case, manual parsing may be needed, but it should still be decoding-aware.
This still requires a decision for malformed pairs and duplicate keys. That decision should be explicit, not accidental.
Typical Deep-Link Use in an Activity
Most Android apps parse query strings from intent.data.
Treat every parameter as optional unless your contract guarantees it. External links are untrusted input.
Validate Values After Parsing
Parsing only tells you that a string has structure. It does not prove the values are valid for your app. After reading query parameters, check types, allowed values, and expected ranges.
For example:
- parse numeric IDs safely with
toLongOrNull() - verify enum-like values against an allowed set
- reject oversized payloads in auth or analytics flows
- confirm state or nonce values before accepting login callbacks
This is where most security and routing bugs actually live.
A good production habit is to keep one shared parsing utility instead of reimplementing query handling in each activity or fragment. That keeps decoding, validation, and duplicate-key behavior consistent across deep links, OAuth callbacks, and analytics routes.
Common Pitfalls
- Manually splitting URLs when
Uriparsing would be safer. - Forgetting repeated keys and silently losing values.
- Reading percent-encoded strings without decoding them.
- Assuming a parsed parameter is trustworthy just because it exists.
- Treating malformed deep links as impossible and skipping tests.
Summary
- Use
UriAPIs first for full URLs and deep links. - Use
getQueryParameterswhen the same key may appear multiple times. - Parse raw query text manually only when you truly do not have a full URI.
- Validate parsed values as untrusted external input.
- Add tests for encoded values, repeated keys, and malformed links.

