<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adrian Kuta on Medium]]></title>
        <description><![CDATA[Stories by Adrian Kuta on Medium]]></description>
        <link>https://medium.com/@adrian.kuta93?source=rss-43ec9398bcbd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yTpqcUe5dNxqejgg.jpg</url>
            <title>Stories by Adrian Kuta on Medium</title>
            <link>https://medium.com/@adrian.kuta93?source=rss-43ec9398bcbd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:10:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adrian.kuta93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Ktor Client for Type-Safe Requests on Android]]></title>
            <link>https://medium.com/@adrian.kuta93/how-to-use-ktor-client-on-android-with-type-safe-requests-be3a60da2aa8?source=rss-43ec9398bcbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3a60da2aa8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ktor]]></category>
            <dc:creator><![CDATA[Adrian Kuta]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 07:40:25 GMT</pubDate>
            <atom:updated>2024-09-04T10:39:40.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aBfRqsFco67-aiA1EFFmg.png" /><figcaption><a href="https://github.com/ktorio/ktor">https://github.com/ktorio/ktor</a></figcaption></figure><h3>Intro</h3><h4>What is Ktor?</h4><p>Ktor is a framework created by JetBrains that is used to create server and client applications in Kotlin. It is designed in a modular way, which means that you can use only those modules that are needed in a given project, which allows you to create lightweight and efficient applications.</p><h4>Definition of Type-safe requests</h4><p>Type-safe requests refer to an approach in HTTP request handling that leverages a strongly-typed programming language (such as Kotlin) to define the structure of requests and responses. In the context of mobile applications, this means that the data types (e.g., JSON, XML) are explicitly defined and validated at compile time, reducing the risk of errors.</p><h3>Installing and configuring Ktor Client in the Android project</h3><p>In this article, I want to take you through a hands-on example of how to use Type-safe arguments with Ktor. Instead of getting bogged down in extensive configuration, we’ll streamline the setup to just what’s necessary, allowing us to focus on the core functionality. To make things even more interesting, we’ll be working with the <a href="https://pixabay.com/api/docs/">Pixabay API</a>, where you’ll see how Type-safe requests can simplify and secure your interactions with a real-world service.</p><h4>Adding dependencies to Gradle</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/314458370c12d489e695d280c953a9d2/href">https://medium.com/media/314458370c12d489e695d280c953a9d2/href</a></iframe><p><strong>ktor-client-android</strong><em> — </em>is a specialized module of the Ktor framework designed to enable HTTP communication on Android devices. It is a part of Ktor’s client-side libraries, which allow developers to make network requests and interact with APIs</p><p><strong>ktor-client-resources</strong> — is a module within the Ktor framework that provides a type-safe way to define and manage RESTful API endpoints. This module enables you to define API routes as Kotlin classes, where each class represents a resource or endpoint in your API. The parameters of the route (such as query parameters or path segments) are modeled as properties of the class.</p><p><strong>ktor-client-content-negotiation </strong>— The module enables automatic content negotiation, meaning it can automatically handle the conversion of data between different formats (like JSON or XML) based on the Content-Type of the response or the Accept header of the request. This module integrates with popular serialization libraries such as kotlinx.serialization, Jackson, and Gson. This allows for seamless serialization of Kotlin data classes to JSON or other formats and vice versa.</p><p><strong>ktor-client-logging</strong> — The module allows you to log various parts of HTTP requests and responses, including headers, bodies, and status codes. This helps in understanding the flow of data and diagnosing issues. This module integrates well with existing logging systems like SLF4J, Logback. On Android, <a href="https://ktor.io/docs/client-logging.html#android">JetBrains recommend</a> to use the SLF4J Android library.</p><p><strong>ktor-serialization-kotlinx-json</strong> — The module leverages the kotlinx.serialization library, which is a Kotlin-native serialization framework, to handle JSON serialization and deserialization. This provides a type-safe and efficient way to work with JSON in Ktor.</p><h4>Configuring Ktor client</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b63d6f1825290dd0673725ea359196c7/href">https://medium.com/media/b63d6f1825290dd0673725ea359196c7/href</a></iframe><p><strong>HttpClient(Android)</strong></p><p>HttpClient(Android) creates a Ktor HttpClient using the Android-specific engine. This engine is optimized to work with Android&#39;s networking stack.</p><p><strong>Install ContentNegotiation</strong></p><p>install(ContentNegotiation) { ... } installs the ContentNegotiation feature, which allows the client to automatically serialize and deserialize data to and from JSON format.</p><p>json(Json { ignoreUnknownKeys = true }) specifies that the kotlinx.serialization library should be used for JSON handling. The ignoreUnknownKeys = true configuration tells the serializer to ignore any unknown keys in the JSON response, which is useful when dealing with APIs that may include extra fields not present in your data models.</p><p><strong>Install Resources</strong></p><p>install(Resources) enables the use of type-safe API endpoints using the ktor-client-resources module. This feature allows you to define API routes as Kotlin classes or objects, making your HTTP interactions more type-safe and structured.</p><p><strong>Install Logging:</strong></p><p>install(Logging) adds logging capabilities to the HttpClient. This will log the details of HTTP requests and responses, which is helpful for debugging and monitoring network interactions.</p><p><strong>Default Request Configuration:</strong></p><p>defaultRequest { ... } sets default settings that will apply to every HTTP request made by this client unless overridden.</p><p>url { ... } configures the base URL for requests.</p><p>protocol = URLProtocol.HTTP specifies that the client should use the HTTP protocol.</p><p>host = &quot;pixabay.com&quot; sets the default host to &quot;pixabay.com&quot;.</p><p>parameters.append(&quot;key&quot;, BuildConfig.PIXABAY_API_KEY) adds a query parameter with the API key to every request.</p><h3>Creating Type-safe requests/responses</h3><p><strong>Get images by query with pagination</strong></p><pre>@Resource(&quot;/api&quot;)<br>internal class PixabayImages(<br>    @SerialName(&quot;q&quot;)<br>    val query: String,<br>    val page: Int,<br>    val pageSize: Int<br>)</pre><p><strong>@Resource(&quot;/api&quot;)</strong></p><p>This annotation comes from the ktor-client-resources module. It marks the PixabayImages class as a resource, meaning it represents an API endpoint.</p><p>The &quot;/api&quot; string indicates the base path of the API endpoint this resource maps to. When you make a request using this resource, Ktor will use this path as the base URL.</p><p><strong>@SerialName(&quot;q&quot;) val query: String</strong></p><p>This parameter represents the search query string that will be sent as part of the API request.</p><p>The @SerialName(&quot;q&quot;) annotation is used to map the Kotlin property name (query) to a different name (q) in the serialized JSON or query parameters. This is useful when the API expects a specific parameter name that differs from your Kotlin property name.</p><p>If you remember we set the base URL and key in the Ktor’s configuration which is why the final query would be sent to the endpoint: http://pixabay.com/api?key=&lt;YOUR_API_KEY&gt;&amp;q=&lt;QUERY&gt;&amp;page=&lt;PAGE_NUMbER&gt;&amp;pageSize=&lt;PAGE_SIZE&gt;</p><p><strong>Get images by id</strong></p><p>A simple example of a class used to request images from pixabay by id</p><pre>@Resource(&quot;/api&quot;)<br>internal class PixabayImagesById(<br>    val id: String,<br>)</pre><p><strong>More resource class examples</strong></p><p><a href="https://ktor.io/docs/client-resources.html#resource_classes">Type-safe requests | Ktor</a></p><h4>Response data model</h4><p>To ensure type safety when handling API responses, create a data class that mirrors the structure of the data returned by the server. This allows to work directly with the data, confident in its accuracy and format. To further simplify the data transformation process, I utilized the kotlinx.serialization library, which automatically serializes and deserializes JSON data into the prepared model. This process is powered by the ktor-serialization-kotlinx-json and ktor-client-content-negotiation modules, which integrate seamlessly with Ktor, enabling automatic conversion between JSON and Kotlin objects. This approach not only makes API communication more readable but also enhances safety by eliminating the risk of type mismatches.</p><pre>@Serializable<br>internal data class SearchPixabayImagesResponse(<br>    val hits: List&lt;PixabayImageResponse&gt;<br>)</pre><pre>@Serializable<br>internal data class PixabayImageResponse(<br>    val id: Int,<br>    val pageURL: String,<br>    val type: String,<br>    val tags: String,<br>    val previewURL: String,<br>    val previewWidth: Int,<br>    val previewHeight: Int,<br>    val webformatURL: String,<br>    val webformatWidth: Int,<br>    val webformatHeight: Int,<br>    val largeImageURL: String,<br>    val imageWidth: Int,<br>    val imageHeight: Int,<br>    val imageSize: Int,<br>    val views: Int,<br>    val downloads: Int,<br>    val likes: Int,<br>    val comments: Int,<br>    val user_id: Int,<br>    val user: String,<br>    val userImageURL: String<br>)</pre><h4>Using a class to execute a Type-safe request</h4><p>This approach simplifies working with APIs by providing a structured, type-safe way to interact with external services, making the codebase more robust and easier to maintain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e22e09807f2ee71db94e65a8cd3d93a8/href">https://medium.com/media/e22e09807f2ee71db94e65a8cd3d93a8/href</a></iframe><p>When making an API call, the request parameters are passed in a type-safe manner, and the response is automatically parsed into the defined data class. This eliminates the need for manual parsing and reduces the risk of errors related to incorrect data handling.</p><p>In summary, using Ktor on Android with type-safe requests allows you to leverage Kotlin’s powerful type system to ensure safe and efficient API interactions. By defining data classes for your API responses and utilizing Ktor’s content negotiation and serialization features, you can seamlessly manage JSON data, enhancing your app’s reliability and maintainability. This approach not only simplifies your code but also reduces the risk of errors, making your Android development experience smoother and more productive.</p><p>Thank you for taking the time to read this article — I hope you found it helpful and informative! 👏👏👏</p><h4>Resources</h4><ul><li><a href="https://github.com/ktorio/ktor">https://github.com/ktorio/ktor</a></li><li><a href="https://ktor.io/docs/client-engines.html">https://ktor.io/docs/client-engines.html</a></li><li><a href="https://ktor.io/docs/client-resources.html">https://ktor.io/docs/client-resources.html</a></li><li><a href="https://github.com/Kotlin/kotlinx.serialization">https://github.com/Kotlin/kotlinx.serialization</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3a60da2aa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android ViewPager with dots indicator]]></title>
            <link>https://medium.com/@adrian.kuta93/android-viewpager-with-dots-indicator-a34c91e59e3a?source=rss-43ec9398bcbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a34c91e59e3a</guid>
            <category><![CDATA[viewpager]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Adrian Kuta]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 09:37:23 GMT</pubDate>
            <atom:updated>2020-03-11T17:39:44.266Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android ViewPager(2) with dots indicator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*HPf9CzK7MrrkZ3Hym2Wdnw.png" /><figcaption>ViewPager with dots indicator</figcaption></figure><p>Implementation of dots indicator for ViewPager <strong>without</strong> any 3rd party libraries. All we need are: <a href="https://developer.android.com/reference/androidx/viewpager/widget/ViewPager?hl=en">ViewPager</a>, <a href="https://developer.android.com/reference/com/google/android/material/tabs/TabLayout?hl=en">TabLayout</a> and 2 drawables for selected and default dots.</p><p>Implementation for ViewPager2 is almost the same:<br>Replace androidx.viewpager.widget.ViewPager with androidx.viewpager2.widget.ViewPager2.</p><p>Firstly, we have to add TabLayout to our screen layout, and connect it with ViewPager. We can do this in two ways:</p><h4><strong>Using nested </strong><strong>TabLayout inside </strong><strong>ViewPager</strong></h4><p>TabLayout supports being used as part of a ViewPager’s decor, and can be added directly to the ViewPager in a layout resource file like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b4c5b41cc85cb12886af65a9dfb0540/href">https://medium.com/media/1b4c5b41cc85cb12886af65a9dfb0540/href</a></iframe><blockquote>Views which are annotated with the <a href="https://developer.android.com/reference/androidx/viewpager/widget/ViewPager.DecorView.html">ViewPager.DecorView</a> annotation are treated as part of the view pagers &#39;decor&#39;. Each decor view&#39;s position can be controlled via its android:layout_gravity attribute.</blockquote><h4>Separate TabLayout</h4><p>We don’t have to place TabLayout inside ViewPager, we can put it elsewhere:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4870bce8d47765f7c84504422da9d9b2/href">https://medium.com/media/4870bce8d47765f7c84504422da9d9b2/href</a></iframe><p>In this case we have to connect TabLayout with ViewPager programmatically:</p><p>for ViewPager by using <a href="https://developer.android.com/reference/com/google/android/material/tabs/TabLayout.html?hl=en#setupwithviewpager">setupWithViewPager(viewPager)</a> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/281fa577fa077a0c7446328b2e426b4b/href">https://medium.com/media/281fa577fa077a0c7446328b2e426b4b/href</a></iframe><p>for ViewPager2 by using TabLayoutMediator :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93bc55eb070eb648452fa7db3f108517/href">https://medium.com/media/93bc55eb070eb648452fa7db3f108517/href</a></iframe><p>Once we created our layout, we have to prepare our dots. So we create three files: selected_dot.xml, default_dot.xml and tab_selector.xml.</p><p><strong>selected_dot.xml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6d5290342297434c0522576ebcd2af8/href">https://medium.com/media/b6d5290342297434c0522576ebcd2af8/href</a></iframe><p><strong>default_dot.xml</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02f00edaea61f65513c7bd08c1914d7e/href">https://medium.com/media/02f00edaea61f65513c7bd08c1914d7e/href</a></iframe><p><strong>tab_selector.xml</strong></p><p>This file will switch between selected_dot.xml and default_dot.xml , depending on the page selected in ViewPager</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2f3993ed03baa3cb643672bb1df0c9a/href">https://medium.com/media/c2f3993ed03baa3cb643672bb1df0c9a/href</a></iframe><p>In the last step, we need to connect tab_selector with TabLayout , to do this we have to add only 3 lines of code to our TabLayout in xml:</p><pre>app:tabBackground=&quot;@drawable/tab_selector&quot;<br>app:tabGravity=&quot;center&quot;<br>app:tabIndicatorHeight=&quot;0dp&quot;</pre><h3>DONE! 👏👏👏</h3><p>Here is code example of dots indicator for ViewPager and ViewPager2</p><p><a href="https://github.com/AdrianKuta/ViewPagerDotsIndicator">AdrianKuta/ViewPagerDotsIndicator</a></p><p><a href="https://www.linkedin.com/in/adrian-kuta-9366b2ba/">LinkedIn</a><br><a href="https://github.com/AdrianKuta">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a34c91e59e3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>