android.net.uri getQueryParameterNames() alternative

android, api, parameters, uri

Solution

The only problem with APIs < 11 is that this method is not implemented. I guess the best idea is to look into Android source code and use implementation from API >= 11. This should get you absolutely identic functionality even on older APIs.

This one is from 4.1.1, modified to take Uri as a parameter, so you can use it right away:

/**
 * Returns a set of the unique names of all query parameters. Iterating
 * over the set will return the names in order of their first occurrence.
 *
 * @throws UnsupportedOperationException if this isn't a hierarchical URI
 *
 * @return a set of decoded names
 */
private Set<String> getQueryParameterNames(Uri uri) {
    if (uri.isOpaque()) {
        throw new UnsupportedOperationException("This isn't a hierarchical URI.");
    }

    String query = uri.getEncodedQuery();
    if (query == null) {
        return Collections.emptySet();
    }

    Set<String> names = new LinkedHashSet<String>();
    int start = 0;
    do {
        int next = query.indexOf('&', start);
        int end = (next == -1) ? query.length() : next;

        int separator = query.indexOf('=', start);
        if (separator > end || separator == -1) {
            separator = end;
        }

        String name = query.substring(start, separator);
        names.add(Uri.decode(name));

        // Move start to end of name.
        start = end + 1;
    } while (start < query.length());

    return Collections.unmodifiableSet(names);
}

If you want to dig into it yourself, here is the original code:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/net/Uri.java?av=f

Problem

I'm looking for an alternative way to get the query parameter names from an android.net.Uri. getQueryParameterNames() require api level 11. I'd like to do the same for any lower level api. I was looking at getQuery() which will return everything after the '?' sign. Would the best way to go about this be to parse that string and search for everything before an '=' and capture that? I simply do not know what query parameters will be presented every time.

Original source