Retrofit2 - Simple basic example

Here, I am going to explain the use of retrofit library in android. The tutorial has two api calls, one to get the model class and another to get the JSON as string. Another point is, according to the response we need, we have to pass the appropriate "ConverterFactory" to retrofit object.

The step by step tutorial

1. First add the dependencies in gradle,


 compile 'com.squareup.retrofit2:retrofit:2.1.0'
 compile 'com.google.code.gson:gson:2.6.2'
 compile 'com.squareup.retrofit2:converter-gson:2.1.0'
 // for scalar converter factory
 compile 'com.squareup.retrofit2:converter-scalars:2.1.0'



2. Then create a ApiInterface class and add the api calls we need. The return type of the methods are "Call". One point to note in Call is execute() call is a synchronize call and enqueue() is an asynchronous call. In addition to that, BASE_URL should end with "/", else we will get an IllegalArgumentException


public interface APIInterface {

    //String BASE_URL = "https://simplifiedcoding.net/demos/";
    String BASE_URL = "https://roads.googleapis.com/v1/";

    @GET("marvel")
    Call> getHeroes();

   @GET("snapToRoads?path=12.8497131,77.6455709|12.9130196,77.6661341|12.9502116,77.6994172|12.9657612,77.7165661&interpolate=true&key=AIzaSyBD- 
   9W3xnDBbwZAfx6CZUo4JL-ixmY2wuY")
   Call getSnapToRoad();
}



3. Now in MainActivity onCreate(), means in UI thread we can call the retrofit API call.


private void getApiCall() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIInterface.BASE_URL)
                //.addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        APIInterface api = retrofit.create(APIInterface.class);
        //Call> call = api.getApiCall();
        Call call = api.getSnapToRoad();
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.e(TAG, "response.isSuccessful: "+response.isSuccessful());
                Log.e(TAG, "response.code: "+response.code());
                if (response.isSuccessful()) {
                    Log.e(TAG, "response.body: " + response.body());
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {

            }
        });
    }



4. Last point is add the INTERNET permission in manifest.


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



The full source code is, here

Happy Coding
Team Androidians

Comments

Popular posts from this blog

Open Gallery and get the selected image in appplication

AlarmManager and Notification in Android

Dismiss or Cancel dialog by swipe gesture