Photo by Anil Kukreti

Basic Usage of Retrofit in Kotlin for fetching JSON

success_anil
The Startup
Published in
4 min readFeb 11, 2020

--

Welcome to a brand new tutorial for Easy Android Programming. In the tutorial, we are going to learn about the basic usage of retrofit in kotlin for fetching JSON from a remote server.

Before starting the tutorial, I would like to tell you, code for the blog is available at Open source Github repository.

Index

Below is the index for various sections of the blog

  1. Motivation
  2. Process
  3. File Organization
  4. Movie.kt
  5. MoviesResponse.kt
  6. MoviesService.kt
  7. MainActivity.kt
  8. Conclusion

Motivation

I would like to quote here, a famous saying by Mr. Charles R Swindoll,

Life is 10% what happens to you and 90% how you react to it.

Process

So how the quote in the last section, pertains to the topic we are going to learn. We can always use our old friend Asynctasks to make networking calls rather than using a networking library like Retrofit.

But when we use retrofit I get below advantages

  • Less line of Code, so clean code which Easy code maintenance for your app in future
  • Time of Execution is one of the areas, where retrofit really shines.

There are several other benefits of using retrofit but let’s stick to the topic.

File Organization

Android Studio Screenshot

Now comes the implementation part, In your module-level build.gradle file you need to add retrofit, and related gson-converter libraries as dependencies.

// retrofit
implementation 'com.squareup.retrofit2:retrofit:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0'

After completing the Gradle sync in your project, you will be ready for using retrofit in your project.

Once this is done, we need to add a few more files like a service interface ( Please don’t get confused with Android Services). These are the files that we require

  • Movie (A model class to hold data pertaining to each movie)
  • MoviesResponse.kt (A model class to hold data pertaining to each movie)
  • MoviesService.kt ( A class that responsible for interacting with REST HTTP URL)

Movie.kt

We will be using https://www.relsellglobal.in/tutorial_blogs/movies.php?year=2001.

Let’s open this URL and we will see JSON code written below

{
moviesArr: [
{
name: "Om Namah sivah",
year: "2001"
},
{
name: "Jai santoshi ma",
year: "2001"
},
{
name: "Jai veer hanumaan",
year: "2001"
}
]
}

Basically, on hitting the URL we got a JSON Response that shows a list of movies in 2001. But we are going to create a mapping object/model which can hold data for a particular movie.

Please focus on the code snippet

{
name: "Om Namah sivah",
year: "2001"
}

So we can create a model class in kotlin mapping above JSON. it may be like below

class Movie{
@SerializedName("name")
var name = ""
@SerializedName("year")
var year = ""
}

MoviesResponse.kt

After the addition of Movies Model class, we need to add a class that will be used for holding the JSON Data in the right format. MoviesResponse class will be assisted by Movie objects. If we see response JSON, we will find moviesArray holds different movie JSON Objects. Hence in kotlin, we write the below code.

class MoviesResponse {
@SerializedName("moviesArr")
var moviesArr = ArrayList<Movie>()
}

MoviesService.kt

As discussed earlier also, we need to add a service interface to assist the app in querying the REST HTTP URL. So in MoviesService.kt file add code for it

interface MoviesService {
@GET("movies.php?")
fun getMoviesList(@Query("year") year : String) : Call<MoviesResponse>
}

We are making an HTTP GET request for fetching data from URL, by passing year as a query string parameter.

MainActivity.kt

Let’s open your MainActivity.kt file

add an instance variable,

var BaseUrl = "https://www.relsellglobal.in/tutorial_blogs/"

Inside your oncreate method, add below line to create an instance of retrofit using builder for the base Url.

val retrofit = Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()

Now we need to create an instance of MovieService

val service = retrofit.create(MoviesService::class.java)

Then we will call the respective method declared in the service class, passing a param

val call = service.getMoviesList("2000")        call.enqueue(object : Callback<MoviesResponse> {
override fun onResponse(call: Call<MoviesResponse>, response: Response<MoviesResponse>) {
if (response.code() == 200) {
val movieResponse = response.body()!!
for( movie in movieResponse.moviesArr){
Log.v("MainActivity", movie.name)
}
}
}
override fun onFailure(call: Call<MoviesResponse>, t: Throwable) {
}
})

So, in the logcat in the android studio, we will see debug statements for different movies name as received from JSON.

Conclusion

This brings us to the end of the blog about the basic usage of Retrofit in Kotlin. A video tutorial for the blog will be available very soon. I Will update the link here.

Thanks for reading.

Happy Coding.

--

--

success_anil
The Startup

Learning via repetition. Long but sturdy, reliable way to learn.