Skip to content
DeveloperMemos

Creating a Uri and Adding Parameters with Uri.parse and appendQueryParameter

Android, Kotlin, Uri.parse, appendQueryParameter1 min read

In Android development, working with URIs (Uniform Resource Identifiers) is essential when dealing with web-based APIs or building dynamic links for your app. A URI represents the address of a resource, such as a website URL. Sometimes, you may need to add parameters to the URI to pass data to the server or customize the behavior of your app. In this article, we will explore how to create a Uri and add parameters using the Uri.parse method and the appendQueryParameter method in Kotlin.

Creating a Uri with Uri.parse

The Uri.parse method allows you to create a Uri by parsing a string representation of it. Here's an example:

1val urlString = "https://example.com/path/to/resource"
2val uri = Uri.parse(urlString)

In the above example, we create a Uri object by parsing the urlString. The resulting uri can be used to represent the specified resource.

Adding Parameters with appendQueryParameter

To add parameters to a Uri, we can use the appendQueryParameter method. This method takes two parameters: the parameter name and its value. Here's an example:

1val baseUri = Uri.parse("https://example.com/search")
2val query = "android"
3val uriBuilder = baseUri.buildUpon()
4uriBuilder.appendQueryParameter("q", query)
5val uriWithQuery = uriBuilder.build()

In the above example, we start with a base Uri (baseUri) representing a search endpoint. We then create a Uri.Builder object using buildUpon method to modify the base Uri. Next, we use the appendQueryParameter method to add the "q" parameter with the value of our search query. Finally, we call build on the Uri.Builder to obtain the final Uri object (uriWithQuery) with the added query parameter.

You can add multiple parameters by calling appendQueryParameter multiple times with different parameter names and values.

Example: Building a Flickr API Query

Let's consider an example where we want to build a Uri for querying photos from the Flickr API. We have a base URL, and we want to add parameters like tags, page number, and per-page count. Here's how we can do it:

1val baseUrl = "https://api.flickr.com/services/rest"
2val apiKey = "your-api-key"
3val tags = "nature"
4val page = 1
5val perPage = 10
6
7val uriBuilder = Uri.parse(baseUrl).buildUpon()
8uriBuilder
9 .appendQueryParameter("method", "flickr.photos.search")
10 .appendQueryParameter("api_key", apiKey)
11 .appendQueryParameter("tags", tags)
12 .appendQueryParameter("page", page.toString())
13 .appendQueryParameter("per_page", perPage.toString())
14
15val flickrApiUri = uriBuilder.build()

In this example, we start with the base URL of the Flickr API and add parameters such as the API key, tags, page number, and per-page count. The resulting flickrApiUri represents the complete query URI that can be used to fetch the desired photos.