Working With Retrofit Library - Android

Retrofit Android Library
1 January 2017

How to use retrofit library

Retrofit is better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a REST client for Android built by Square. By using this tool android developer can make all network stuff much more easier like parsing json, doing crud operations.

Step1:- Including Retrofit
For including retrofit we have to add Retrodit dependency in gradle.

dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
      compile 'com.android.support:appcompat-v7:23.4.0'
      compile 'com.squareup.retrofit2:retrofit:2.1.0'
      compile 'com.squareup.retrofit2:converter-gson:2.1.0'
      compile 'com.squareup:otto:1.3.8'
}

Step2:- Adding Internet Permission in Manifest
Since we are using internet connection we have to ask permission to access internet and for that we have to add Internet Permission in Android Manifest file.

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

Now we need an api which can return JSON data. If you have your own api its good. But if you dont have your own api use our test api "https://hashtagsolutions.in/blog/api/test" .
It Returns following result

{
     "name": "How to use retrofit library",
     "type": "Blog Post",
     "url": "https://www.hashtagsolutions.in/blog/android-how-to-implement-retrofit-library",
     "author": "Lakshay Jain"
}

Step3:- Create POJO Class
We need to create a response pojo class which will store all data.

package in.hashtagsolutions.retrofit;

import com.google.gson.annotations.SerializedName;

  public class ApiResponse{

    @SerializedName("name")
    private String name;

    @SerializedName("type")
    private String type;

    @SerializedName("url")
    private String url;

    @SerializedName("author")
    private String author;

     public String getName() {
          return name;
    }

    public String getType() {
          return type;
    }

     public String getUrl() {
         return url;
    }

    public String getAuthor() {
          return author;
     }

   }

Step4:- Create Api Interface
We need to create a retrofit api interface class

package in.hashtagsolutions.retrofit;

import in.hashtagsolutions.retrofit.ApiResponse;
import retrofit2.http.GET;
import retrofit2.Call;

  public class ApiInterface{

     @GET("blog/api/test")
     Call<ApiResponse> getBlog();

   }

Step5:- Create Rest Client
Now we need to create retrofit client so we can call it in our main activity

package in.hashtagsolutions.retrofit;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

  public class RestClient{

     public static final String BASE_URL = "https://www.hashtagsolutions.in/";

     public static Retrofit getClient() {
          Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
               .addConverterFactory(GsonConverterFactory.create())
               .build();
           return retrofit;
        }

   }

Step6:- Getting json result on your activity
Lets make the first request from our Main Activity

  public class MainActivity extends AppCompatActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       //Creating Api Interface
       ApiInterface apiService = RestClient.getClient().create(ApiInterface.class);
       Call <ApiResponse> call = apiService.getBlog();
        call.enqueue(new Callback<ApiResponse>() {

           @Override
          public void onResponse(Call <ApiResponse>call, Response <ApiResponse> response) {
             ApiResponse apiresponse = response.body();
             String name= apiresponse.getName();
             String url= apiresponse.getUrl();
             String author= apiresponse.getAuthor();
             String type= apiresponse.getType();
             //Do Something with response
           }

           @Override
           public void onFailure(Call<ApiResponse>call, Throwable t) {
             // Log error here since request failed
             Log.e("Error Response", t.toString());
              }
           });
        }

   }

Now just build and run the application and we get the api result.


By Lakshay Jain

Tags: Android, Retrofit