Replace query parameters in Uri.Builder in Android?

Dhiraj Gupta picture Dhiraj Gupta · Mar 6, 2015 · Viewed 11.3k times · Source

I'm passing around a Uri.Builder object as a mechanism for subclasses to fill in whatever parameters necessary into a Uri before it is executed in Android.

Problem is, one of the parameters that the base class adds using builder.appendQueryParameter("q",searchPhrase); needs to be replaced in the sub-class, but I can only find appendQueryParameter(), there is no replace or set method. appendQueryParameter() with the same parameter name adds another instance of the parameter, doesn't replace it.

Should I give up and try another way? Or is there a way to replace query parameters that I haven't found yet?

Answer

Nachi picture Nachi · Oct 20, 2015

Since there is no in-built method, the best way I have found is to build a new Uri. You iterate over all the query parameters of the old Uri and then replace the desired key with the new value.

private static Uri replaceUriParameter(Uri uri, String key, String newValue) {
    final Set<String> params = uri.getQueryParameterNames();
    final Uri.Builder newUri = uri.buildUpon().clearQuery();
    for (String param : params) {
        newUri.appendQueryParameter(param, 
            param.equals(key) ? newValue : uri.getQueryParameter(param));
    }

    return newUri.build();
}