Tuesday, October 13, 2015

Android & Retrofit 2.0

Retrofit is a well known and very popular networking library. It is an open source library created by Square and it is widely used by Android developers because it performs great and is easy to implement.

Retrofit 2.0 introducing new features, such as cancelling a request or using a pattern that fits both synchrone and asynchrone requests. Also it does no longer depend on just Gson.

Now you need to add a converter as a separate dependency, which gives you more flexibility if you want to convert a response into an object. You can use the Gson converter but you can also choose another converter to support a different data format, such as Xml. Or you can create your own converter if you want to.

Retrofit dependencies

Here is a small demo project that consumes data from Wipmania using RetroFit 2.0. WipMania is a service that determines the location based on your IP address.

1. Create a new project in Android Studio and add the dependencies for RetroFit in the build.gradle file in the app folder. The dependency section will look like shown below.

compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'  
compile 'com.squareup.okhttp:okhttp:2.4.0'  
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'

2. Define the API endpoint in an interface called IRepository

import retrofit.Call;
import retrofit.http.GET;

public interface IRepository {

    Call demoCall();

3. Create a new class, name it Result and add some of the fields being returned by the WipMania service.

public class Result {

        public String latitude;
        public String longitude;
        public Address address;

        public class Address{
            public String continent;
            public String country;

4. Create a method testRetrofit in your MainActivity. Within this method setup Retrofit and call the method from the interface we have created. The API returns data in a JSON format. The GsonConverterFactory will convert that data into a Result object.

If the call succeeds we will display some of the properties of the returned data in a toast or if it fails we will display an error.

import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;


public static final String BASE_URL = "http://api.wipmania.com/";

private void testRetroFit(){

   Retrofit retrofit = new Retrofit.Builder().

   IRepository repository = retrofit.create(IRepository.class);

   Call call = repository.demoCall();
   call.enqueue(new Callback() {
       public void onResponse(Response response, 
         Retrofit retrofit) {

       public void onFailure(Throwable t) {

private void displaySuccess(Result result){
      " lng="+result.longitude+ 
       " continent="+result.address.continent+"   

private void displayError(){
    Toast.makeText(this,"something went wrong", 
5. Call the testRetroFit method from somewhere in your app, for example in the onStart method. Do not forget to add the internet permission to your AndroidManifest file. Finally run your app.
<uses-permission android:name="android.permission.INTERNET"/>

Cancel a transaction

6. What if the user initiates a request but changes his mind? Previously Retrofit had not a straight way to cancel an ongoing transaction but that is no longer an issue. Just call the cancel method on the Call object.


So far it seems Retrofit 2.0 is a really great improvement and I have just seen the beta version. Also there some other interesting features to investigate...

Further reading...

No comments:

Post a Comment