Use URI builder in Android or create URL with variables

February 12, 2016 - Android, Uncategorized

Let’s say that I want to create the following URL:
To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
.appendQueryParameter(“type”, “1”)
.appendQueryParameter(“sort”, “relevance”)
String myUrl =;

//Second Way

There is another way of using Uri and we can achieve the same goal
To build the Uri you can even use this

final String FORECAST_BASE_URL =
final String QUERY_PARAM = “q”;
final String FORMAT_PARAM = “mode”;
final String UNITS_PARAM = “units”;
final String DAYS_PARAM = “cnt”;
You can declare all this the above way or even inside the Uri.parse() and appendQueryParameter()

Uri builtUri = Uri.parse(FORECAST_BASE_URL)
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, “json”)
.appendQueryParameter(UNITS_PARAM, “metric”)
.appendQueryParameter(DAYS_PARAM, Integer.toString(7))
At last

URL url = new URL(builtUri.toString());

Leave a Reply