2

I want to create url with dynamic parameters ?

new Uri.Builder()
.scheme("http")
.authority("foo.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();

the above Uri class is member of android.net

I have unknown number of params , How can I create dynamic url when I don't know the number of parameters ?

Jayesh
  • 3,661
  • 10
  • 46
  • 76
  • 1
    you already answered your question: .appendQueryParameter – pskink May 14 '14 at 09:38
  • dude in My answer two parameters are appended , I have multiple parameters for append and I don't know the numbers of parameter – Jayesh May 14 '14 at 09:45
  • buddy, I know the parameters, but number of parameters is dynamic (not fixed) – Jayesh May 14 '14 at 09:49
  • so what? iterate over them and call appendQueryParameter... its so easy, whats the problem? – pskink May 14 '14 at 09:50
  • can you please give me solution by code? I have parameters in ArrayListList now give me solution bro – Jayesh May 14 '14 at 09:53
  • b = new Uri.Builder(); foreach(key in something) {b.appendQueryParameter(key, value); } – pskink May 14 '14 at 09:55
  • Uri b = new Uri.Builder(); not working , giving compile time error, message is "Change type of 'b' to 'Builder' " and also we cant append parameters after build the uri, we must specify that at the time of building uri – Jayesh May 14 '14 at 09:58
  • whem you use new Uri.Builder() so b should be declared as Uri.Builder and nor Uri, then call appendQueryParameter x times and finally call build to get the Uri, that is how builders work – pskink May 14 '14 at 10:00
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/52658/discussion-between-jayesh-and-pskink) – Jayesh May 14 '14 at 10:02

1 Answers1

2

Given that the nameValuePairs are set before you can first declare the URIBuilder and then add all parameters with their keys in iterative manner through the List.

Uri uri;
Uri.Builder builder = new Uri.Builder();
    builder.scheme("http")
    .encodedAuthority("foo.com")
    .appendEncodedPath("someservlet");

    for (NameValuePair l : nameValuePairs)
    {
        builder.appendQueryParameter(l.getName(), l.getValue());
    }

    uri = builder.build();

Finally you can get the Uri object from the builder object.

For reference how to build a List of NameValuePair please refer to this post: What is the use of List<NameValuePair> or ArrayList<NameValuePair>

Community
  • 1
  • 1
Vas Giatilis
  • 1,086
  • 12
  • 16