Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace query parameters in Uri.Builder in Android?

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?

like image 665
Dhiraj Gupta Avatar asked Mar 06 '15 11:03

Dhiraj Gupta


People also ask

Can URI have query parameters?

URI parameter (Path Param) is basically used to identify a specific resource or resources whereas Query Parameter is used to sort/filter those resources. Let's consider an example where you want identify the employee on the basis of employeeID, and in that case, you will be using the URI param.

Is replaced by %2F?

Forward slash is being replaced by %2F in the latest release (0.2. 12).

What are URI parameters and query parameters?

A URI parameter identifies a specific resource whereas a Query Parameter is used to sort or filter resources.

What do you call a parameter added to the URI?

URL parameters (known also as “query strings” or “URL query parameters”) are elements inserted in your URLs to help you filter and organize content or track information on your website.


1 Answers

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();
}
like image 145
Nachi Avatar answered Nov 15 '22 04:11

Nachi