<?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 Guru Karthi on Medium]]></title>
        <description><![CDATA[Stories by Guru Karthi on Medium]]></description>
        <link>https://medium.com/@gurukarthi.android?source=rss-ec06c6bd8a58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aNDppzfciMr8vooL.</url>
            <title>Stories by Guru Karthi on Medium</title>
            <link>https://medium.com/@gurukarthi.android?source=rss-ec06c6bd8a58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:03:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gurukarthi.android/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[Kotlin: Android + RetroFit + LoganSquare]]></title>
            <link>https://medium.com/@gurukarthi.android/kotlin-android-retrofit-logansquare-cc1c3e8d07e9?source=rss-ec06c6bd8a58------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc1c3e8d07e9</guid>
            <category><![CDATA[retrofit2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[logan-square]]></category>
            <category><![CDATA[retrofit]]></category>
            <dc:creator><![CDATA[Guru Karthi]]></dc:creator>
            <pubDate>Sun, 11 Jun 2017 17:12:49 GMT</pubDate>
            <atom:updated>2017-10-29T21:03:53.478Z</atom:updated>
            <content:encoded><![CDATA[<p>Good to start by saying happy coding. And thanks for the JetBrains team for giving us a wonderful coding language Kotlin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9IhfGjbByiIWnpES0o2Aqg.png" /><figcaption>Happy Coding with Kotlin</figcaption></figure><p>In this article, I would like to cover the usage of a network library(retrofit), a parser(loganSquare) with Android, using Kotlin.</p><p>Lets Begin..,<br>Being a developer, we have encountered situations like <em>“Ya, But why?”</em>. Here Kotlin gives us a new perspective to say <em>“Ya, for this..”</em>.</p><p>So, I have planned to give a sample and cover the topics on life-saver tools of a typical developer using Kotlin.</p><p>In this, we’re gonna use this <a href="https://jsonplaceholder.typicode.com/photos">link</a> for a simple JSON response from the API.</p><p>This API will give us a list of items as illustrated below</p><pre>{<br> “albumId”: 1,<br> “id”: 2,<br> “title”: “reprehenderit est deserunt velit ipsam”,<br> “url”: “<a href="http://placehold.it/600/771796">http://placehold.it/600/771796</a>&quot;,<br> “thumbnailUrl”: “<a href="http://placehold.it/150/771796">http://placehold.it/150/771796</a>&quot;<br> },...</pre><p>I’m going to create a new project in Android Studio and naming “Album”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAIGeNI-GjpXpW9BdMeQNw.png" /></figure><p>Choose the default form factors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*sHJtEFxZfIVd-L5SUzZifQ.png" /></figure><p>I’m going to start with empty screen(Activity)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1gciJCX3VEdNjn5uBx3cA.png" /></figure><p>And I’m naming that as LaunchActivity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*9KKHAuequoGyaZzT8LoN4g.png" /></figure><p>Ola! We have created the project successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*28AEnEKf7Fu6bmX3mdlJtg.png" /></figure><p>Therefore, the very difficult process is done. “<em>Just kidding :)”</em></p><p>Next being in your LaunchActivity go to file menu’s Code-&gt; and click Convert Java files to Kotlin files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*RU1o7VOs2D6YWtRg9Op__g.png" /></figure><p>Our LaunchActivity should look like this now,</p><pre><strong>class </strong>LaunchActivity : AppCompatActivity() {<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_launch</em>)<br>    }<br>}</pre><p>Your project will ask you to change the configuration by syncing<strong> </strong>Gradle. And continue the process by confirming “All modules containing Kotlin files: app”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*9b6DkJqMjdy8M3iRgRgeNA.png" /></figure><p>Now you can see a new line which is added in your app’s build.gradle something like this.</p><pre>compile <strong>&quot;org.jetbrains.kotlin:kotlin-stdlib-jre7:</strong>$kotlin_version<strong>&quot;</strong></pre><p>This is where the actual game begins. We need to include the following dependencies in our app’s build.gradle.</p><pre>compile <strong>&#39;com.bluelinelabs:logansquare:1.3.6&#39; </strong><em>//JSON parsing and serializing library<br></em>compile <strong>&#39;com.github.aurae.retrofit2:converter-logansquare:1.4.1&#39; </strong><em>//Converter for loganSquare JSON serializer for RetroFit.<br></em>compile <strong>&#39;com.squareup.retrofit2:retrofit:2.1.0&#39; </strong><em>//Network library<br></em>compile <strong>&#39;com.squareup.okhttp3:logging-interceptor:3.3.1&#39; </strong><em>//logs HTTP request and response data<br></em>kapt <strong>&#39;com.bluelinelabs:logansquare-compiler:1.3.5&#39;<br><br></strong>compile <strong>&#39;com.github.bumptech.glide:glide:3.7.0&#39;</strong><em>// To load and render photo from URL</em></pre><p>Assuming that we have added dependencies, We need to create the DTO<em> (Data Transfer Object)</em> for Album to adopt the API’s JSON data.</p><pre><strong>package </strong>com.droidmob.album<br><br><strong>import </strong>com.bluelinelabs.logansquare.annotation.JsonField<br><strong>import </strong>com.bluelinelabs.logansquare.annotation.JsonObject</pre><pre>@JsonObject(fieldDetectionPolicy = JsonObject.FieldDetectionPolicy.<strong>NONPRIVATE_FIELDS_AND_ACCESSORS</strong>)<br><strong>class </strong>AlbumDto(<br>        @JsonField(name = <em>arrayOf</em>(<strong>&quot;id&quot;</strong>))<br>        <strong>var _id</strong>: Int = -1,<br>        @JsonField(name = <em>arrayOf</em>(<strong>&quot;albumId&quot;</strong>))<br>        <strong>var albumId</strong>: Int = -1,<br>        @JsonField(name = <em>arrayOf</em>(<strong>&quot;title&quot;</strong>))<br>        <strong>var title</strong>: String? = <strong>null</strong>,<br>        @JsonField(name = <em>arrayOf</em>(<strong>&quot;url&quot;</strong>))<br>        <strong>var url</strong>: String? = <strong>null</strong>,<br>        @JsonField(name = <em>arrayOf</em>(<strong>&quot;thumbnailUrl&quot;</strong>))<br>        <strong>var thumbnailUrl</strong>: String? = <strong>null<br></strong>)</pre><pre>//Our JSON data</pre><pre>{<br> “albumId”: 1,<br> “id”: 2,<br> “title”: “reprehenderit est deserunt velit ipsam”,<br> “url”: “<a href="http://placehold.it/600/771796">http://placehold.it/600/771796</a>&quot;,<br> “thumbnailUrl”: “<a href="http://placehold.it/150/771796">http://placehold.it/150/771796</a>&quot;<br> },...</pre><p>If you look closely into our DTO and JSON data you can identify the field name “id” of JSON data is illustrated as “_id” in DTO.</p><p>For that particular field, we have added explicit method to parse/serialize parameter to match with JSON data using @JsonField annotation.</p><pre> @<em>JsonField(name = arrayOf(“&lt;fieldName&gt;”))</em></pre><p>Let’s jump into creating RetroFit client class and ApiInterface.</p><pre>//ApiClient.kt</pre><pre><strong>import </strong>com.droidmob.album.ApiInterface<br><strong>import </strong>com.github.aurae.retrofit2.LoganSquareConverterFactory<br><strong>import </strong>retrofit2.Retrofit<br><br><br><strong>object </strong>ApiClient {<br><br>    <strong>val retrofit</strong>: Retrofit = Retrofit.Builder()<br>            .baseUrl(<strong>&quot;https://jsonplaceholder.typicode.com&quot;</strong>)<br>            .addConverterFactory(LoganSquareConverterFactory.create())<br>            .build()<br>    <strong>val apiInterface</strong>: ApiInterface<br><br>    <strong>init </strong>{<br>        <strong>apiInterface </strong>= <strong>retrofit</strong>.create(ApiInterface::<strong>class</strong>.<em>java</em>)<br>    }<br>}</pre><blockquote>In Kotlin, We have to mention the class which needs to act as Singleton using the keyword “<strong>object</strong>”. After scala, I feel Kotlin is so easier to create a singleton class</blockquote><p>To create RetroFit client object, We have three steps</p><ul><li>Create Builder (Retrofit.Builder())</li><li>Configure Base URL (.baseUrl(<strong>“&lt;url&gt;&quot;</strong>))</li><li>Add Factory Converter (addConverterFactory())</li></ul><p>In this, we are adding LoganSquare’s Factory converter to parse DTO to JSON and vice versa.</p><p>And we are creating the instance for the ApiInterface here, Inside the initializer &lt;init&gt; block with the help of RetroFit client instance.</p><blockquote>In Kotlin, initializer (<strong>init</strong>)the block which executes before an object gets instantiated. And these are used for declaring the class body properly.</blockquote><pre>//ApiInterface.kt</pre><pre><strong>import </strong>retrofit2.Call<br><strong>import </strong>retrofit2.http.GET</pre><pre><strong>interface </strong>ApiInterface {<br>    @GET(<strong>&quot;/photos&quot;</strong>)<br>    <strong>fun </strong>getAlbum(): Call&lt;List&lt;AlbumDto&gt;&gt;<br>}</pre><p>We are all set for the network API call. We have DTO to model the JSON data, RetroFit’s client to originate network call, ApiInteface to decide the endpoints. Now, all we wanted to do is to implement and create an environment to make the network API call using all these items.</p><p>After all this, we need to go back to our LaunchActivity.</p><pre><strong>class </strong>LaunchActivity : AppCompatActivity(){<br><br>    <strong>private val TAG</strong>: String = <em>javaClass</em>.<em>simpleName<br>    </em><strong>private var photoListView</strong>: RecyclerView? = <strong>null<br><br>    override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_launch</em>)<br>        <strong>photoListView </strong>= findViewById(R.id.<em>list_album</em>) <strong>as </strong>RecyclerView<br>        <strong>photoListView</strong>!!.<em>layoutManager </em>= GridLayoutManager(<strong>this</strong>, 2, LinearLayoutManager.<em>VERTICAL</em>, <strong>false</strong>)<br>    }<br>}</pre><p>Don’t panic, I just included a RecyclerView in activity_launch.xml, created a custom RecyclerView adapter and declared the variables to fasten our story and don’t worry will share you the code at the end of this article.</p><p>Now we need to invoke the network call using ApiClient’s ApiInterface. But before that, we need to implement an interface (<em>CallBack</em>) to listen to the network operations like successful and failure response.</p><pre><strong>class </strong>LaunchActivity : AppCompatActivity(), Callback&lt;List&lt;AlbumDto&gt;&gt; {...</pre><pre><strong>override fun </strong>onResponse(call: Call&lt;List&lt;AlbumDto&gt;&gt;?, response: Response&lt;List&lt;AlbumDto&gt;&gt;?) {<br>}<br><br><strong>override fun </strong>onFailure(call: Call&lt;List&lt;AlbumDto&gt;&gt;?, t: Throwable?) {<br><br>}</pre><p>In the above code snippet, onResponse method will be executed when we get something as the response from the server. And the onFailure method will be executed if we get any network errors.</p><p>Now, we need to filter the success and failure response using a validation inside the onResponse method.</p><pre><strong>override fun </strong>onResponse(call: Call&lt;List&lt;AlbumDto&gt;&gt;?, response: Response&lt;List&lt;AlbumDto&gt;&gt;?) {<br>    <strong>if </strong>(response!!.<em>isSuccessful </em>&amp;&amp; response.body() != <strong>null</strong>) {<br>        <strong>photoListView</strong>?.<em>adapter </em>= AlbumAdapter(response.body() <strong>as </strong>List&lt;AlbumDto&gt;)<br>    }<br>}<br><br><strong>override fun </strong>onFailure(call: Call&lt;List&lt;AlbumDto&gt;&gt;?, t: Throwable?) {<br>    Toast.makeText(<strong>this</strong>, <strong>&quot;Something went wrong!&quot;</strong>, Toast.<em>LENGTH_SHORT</em>).show()<br>}</pre><p>This is how our LaunchActivity should look now.</p><pre>//LaunchActivity.kt</pre><pre><strong>import </strong>android.os.Bundle<br><strong>import </strong>android.support.v7.app.AppCompatActivity<br><strong>import </strong>android.support.v7.widget.GridLayoutManager<br><strong>import </strong>android.support.v7.widget.LinearLayoutManager<br><strong>import </strong>android.support.v7.widget.RecyclerView<br><strong>import </strong>android.widget.Toast<br><strong>import </strong>com.droidmob.vijay_61.model.webservice.ApiClient<br><strong>import </strong>retrofit2.Call<br><strong>import </strong>retrofit2.Callback<br><strong>import </strong>retrofit2.Response<br><br><strong>class </strong>LaunchActivity : AppCompatActivity(), Callback&lt;List&lt;AlbumDto&gt;&gt; {<br><br>    <strong>private val TAG</strong>: String = <em>javaClass</em>.<em>simpleName<br>    </em><strong>private var photoListView</strong>: RecyclerView? = <strong>null<br><br>    override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_launch</em>)<br>        <strong>photoListView </strong>= findViewById(R.id.<em>list_album</em>) <strong>as </strong>RecyclerView<br>        <strong>photoListView</strong>!!.<em>layoutManager </em>= GridLayoutManager(<strong>this</strong>, 2, LinearLayoutManager.<em>VERTICAL</em>, <strong>false</strong>)<br>        ApiClient.<strong>apiInterface</strong>.getAlbum().enqueue(<strong>this</strong>)<br>    }<br><br><br>    <strong>override fun </strong>onResponse(call: Call&lt;List&lt;AlbumDto&gt;&gt;?, response: Response&lt;List&lt;AlbumDto&gt;&gt;?) {<br>        <strong>if </strong>(response!!.<em>isSuccessful </em>&amp;&amp; response.body() != <strong>null</strong>) {<br>            <strong>photoListView</strong>?.<em>adapter </em>= AlbumAdapter(response.body() <strong>as </strong>List&lt;AlbumDto&gt;)<br>        }<br>    }<br><br>    <strong>override fun </strong>onFailure(call: Call&lt;List&lt;AlbumDto&gt;&gt;?, t: Throwable?) {<br>        Toast.makeText(<strong>this</strong>, <strong>&quot;Something went wrong!&quot;</strong>, Toast.<em>LENGTH_SHORT</em>).show()<br>    }<br>}</pre><p>That’s all, we are good to go.</p><p><a href="https://github.com/HungerNHeart/Kotlin-Android-Retrofit-LoganSquare.git">https://github.com/HungerNHeart/Kotlin-Android-Retrofit-LoganSquare.git</a></p><p>Thanks for reading my ever first article..</p><p>Questions? Comments? Suggestions? Leave a note here or email me at gurukarthi.android@gmail.com</p><p><a href="https://github.com/HungerNHeart"><strong>GitHub</strong></a><strong> </strong><a href="https://twitter.com/hungernheart"><strong>Twitter</strong></a><strong> </strong><a href="https://www.facebook.com/guru.karthi.355"><strong>Facebook</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc1c3e8d07e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>