Retrofit android example [step by step]

In this Retrofit Android tutorial, I am going to explain how to use Retrofit REST client to consume the Rest Web services.Basically, Retrofit developed by square and It’s a type-safe REST client for Android.

In this post, I am explaining code in java. Please check my another post for Retrofit example in Kotlin.

Retrofit official document says,

"A type-safe HTTP client for Android and Java"

With this post, I have created video for this retrofit android studio example.

Advantages of Android Retrofit

  •      Retrofit is dead-simple to use. It essentially lets you treat API calls as simple Java method calls, so you only define which URLs to hit and the types of the request/response parameters as Java classes.  
  •      The entire network call + JSON/XML parsing is completely handled by it (with help from Gson for JSON parsing), along with support for arbitrary formats with pluggable serialization/deserialization.

Android Retrofit Speed

Compare with Volley and AsyncTask, Retrofit providing the very fast response to the request.

Done with the theory part, Let’s get into the code part.

5 step to create retrofit android example

  1.  Add the retrofit dependency
  2. Creating Model Class
  3. Create The Retrofit Instance
  4. Setting Up The Retrofit Interface
  5. Consume The REST Web Service
  6. Set Retrofit response data into the Recyclerview

1. Add the retrofit dependency

Firstly, Add Internet Permission to your Application in AndroidManifest.xml,

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Then, We have to add the retrofit dependency into our build.grade file. We can find the latest retrofit version in the official retrofit website. http://square.github.io/retrofit/

implementation 'com.squareup.retrofit2:retrofit:'+rootProject.retrofit_version

And the GSON converter from retrofit used to convert the JSON response from the server.

implementation 'com.squareup.retrofit2:converter-gson:'+rootProject.retrofit_version

2. Creating Model Class

Before creating the model, we need to know what type of response we will be receiving.

[  
   {  
      "id":"1",
      "image":"http://velmm.com/images/bottom_navigationview/coco.jpg",
      "title":"Coco"
   },
   {  
      "id":"2",
      "image":"http://velmm.com/images/bottom_navigationview/terminator_2.jpg",
      "title":"Terminator 2: Judgment Day 3D"
   },
   {  
      "id":"3",
      "image":"http://velmm.com/images/bottom_navigationview/dunkirk.jpg",
      "title":"Dunkirk"
   },
   {  
      "id":"4",
      "image":"http://velmm.com/images/bottom_navigationview/the_salesman.jpg",
      "title":"The Salesman"
   },
   {  
      "id":"5",
      "image":"http://velmm.com/images/bottom_navigationview/lion.png",
      "title":"Lion"
   },
   {  
      "id":"6",
      "image":"http://velmm.com/images/bottom_navigationview/star_war.jpg",
      "title":"Star Wars: The Last Jedi"
   },
   {  
      "id":"7",
      "image":"http://velmm.com/images/bottom_navigationview/thor_ragnarok.jpg",
      "title":"Thor: Ragnarok"
   },
   {  
      "id":"8",
      "image":"http://velmm.com/images/bottom_navigationview/blade_runner_2049.jpg",
      "title":"Blade Runner 2049"
   },
   {  
      "id":"9",
      "image":"http://velmm.com/images/bottom_navigationview/borg_mcenroe.jpg",
      "title":"Borg McEnroe"
   },
   {  
      "id":"10",
      "image":"http://velmm.com/images/bottom_navigationview/wonder.jpg",
      "title":"Wonder"
   }
]

In my JSON response, I am having the list of movies with name, year and director properties. So, My Model class will be like Movie as class name and name, year, director are properties.

Movie.java

class Movie {

    @SerializedName("title")
    private String title;

    @SerializedName("image")
    private String imageUrl;

    public Movie(String title, String imageUrl) {
        this.title = title;
        this.imageUrl = imageUrl;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}

@SerializedName is used to map the POJO object into to JSON response properties.

3.Create The Retrofit Instance

We need to create the Retrofit instance to send the network requests. we need to use the Retrofit Builder class and specify the base URL for the service.

ApiClient.java

public class ApiClient {
    public static String BASE_URL ="http://velmm.com/apis/";
    private static Retrofit retrofit;
    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

4.Setting Up The Retrofit Interface

Retrofit provides the list of annotations for each HTTP methods:

@GET, @POST, @PUT, @DELETE, @PATCH or @HEAD.

The endpoints are defined inside of an interface using retrofit annotations to encode details about the parameters and request method. T return value is always a parameterized Call<T>.

Because the POJO classes are wrapped into a typed Retrofit Call class.

Method Parameters :

@Body – Sends Java objects as the request body.

@Url – use dynamic URLs.

@Query – We can simply add a method parameter with @Query() and a query parameter name, describing the type.

To URL encode a query using the form:
@Query(value = “auth_token”,encoded = true) String auth_token

ApiInterface.java

public interface ApiInterface {

    @GET("volley_array.json")
    Call<List<Movie>> getMovies();
}

5.Consume The REST Web Service

All the setup are done. Now we are ready to consume the REST web service. In Our MainActivity.Java, First, need to initialize the ApiClient.

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

After the initialization, we to call the getMovies() interface and implement the CallBacks. Part of the Implementation we need to override the onResponse() and onFailure().

If the request succeeds the callback will come into onResponse(). If any error in the request the callback will go into onFailure() method. In onResponse() method, we can get our response from response body.

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<Movie>> call = apiService.getMovies();
call.enqueue(new Callback<List<Movie>>() {
    @Override
    public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
    }   

    @Override
    public void onFailure(Call<List<Movie>> call, Throwable t) {
        Log.d("TAG","Response = "+t.toString());
    }
});

Now our data is received in onReceive() . We can use the data for our application purpose. In this example, I am using this retrofit data to setup in recyclerview.

 

6.Set Retrofit response data into the Recyclerview

In this post, I am skipping the recyclerview setup details. I have explained recyclerview in detail.

set the received response into recyclerview.

recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerAdapter = new RecyclerAdapter(getApplicationContext(),movieList);
        recyclerView.setAdapter(recyclerAdapter);

        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        Call<List<Movie>> call = apiService.getMovies();

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                movieList = response.body();
                Log.d("TAG","Response = "+movieList);
                recyclerAdapter.setMovieList(movieList);
            }

            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d("TAG","Response = "+t.toString());
            }
        });

That's with the coding part. final output,

Download this retrofit android example in Java.

Download this retrofit android example in kotlin.

Conclusion

Thanks for reading this post. This is very basic example with retrofit android. You can try this retrofit android example and let me know your feedback in comments.

Also, Please read my another post using retrofit,

31 Replies to “Retrofit android example [step by step]”

  1. Hello! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done a outstanding job!|

  2. What’s Happening i’m new to this, I stumbled upon this I have found It absolutely helpful and it has aided me out loads. I’m hoping to contribute & help other customers like its helped me. Great job.|

  3. I have been surfing on-line greater than 3 hours these days, but I never discovered any fascinating article like yours. It’s pretty value sufficient for me. Personally, if all site owners and bloggers made just right content material as you did, the internet will probably be much more useful than ever before.|

  4. I like the valuable information you provide for your articles. I’ll bookmark your blog and take a look at once more here regularly. I am slightly sure I will be told many new stuff right here! Best of luck for the following!|

  5. I was suggested this website by way of my cousin. I’m no longer certain whether this put up is written by way of him as nobody else know such precise about my problem. You’re incredible! Thank you!|

  6. Good day! I could have sworn I’ve visited your blog before but after looking at some of the articles I realized it’s new to me. Regardless, I’m definitely pleased I came across it and I’ll be book-marking it and checking back often!|

  7. Great beat ! I wish to apprentice whilst you amend your site, how could i subscribe for a weblog site? The account aided me a appropriate deal. I were tiny bit acquainted of this your broadcast provided vivid transparent idea|

  8. Hi would you mind letting me know which webhost you’re utilizing? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot quicker then most. Can you recommend a good web hosting provider at a fair price? Thanks, I appreciate it!|

  9. My brother recommended I might like this web site. He was entirely right. This post truly made my day. You can not imagine just how much time I had spent for this info! Thanks!|

  10. Great post. I was checking constantly this blog and I’m impressed! Very helpful info particularly the last part I care for such information much. I was seeking this certain information for a very long time. Thank you and good luck.|

  11. Hi i am kavin, its my first occasion to commenting anyplace, when i read this post i thought i could also make comment due to this good paragraph.|

  12. I’m impressed, I must say. Rarely do I come across a blog that’s equally educative and amusing, and without a doubt, you have hit the nail on the head. The issue is something that too few people are speaking intelligently about. I am very happy that I came across this in my search for something regarding this.|

  13. I loved as much as you will receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an nervousness over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly a lot often inside case you shield this increase.|

  14. Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!|

  15. You’ve made some really good points there. I looked on the net to find out more about the issue and found most people will go along with your views on this web site.|

  16. When some one searches for his required thing, therefore he/she wants to be available that in detail, therefore that thing is maintained over here.|

  17. I’ve been surfing online more than 3 hours nowadays, but I never found any fascinating article like yours. It is pretty value enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the web will be much more helpful than ever before.|

  18. Hey would you mind letting me know which hosting company you’re utilizing? I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot faster then most. Can you recommend a good web hosting provider at a honest price? Thanks, I appreciate it!|

Leave a Reply

Your email address will not be published. Required fields are marked *