Android Retrofit


Android Retrofit Tutorial and Examples.

What is Retrofit? Well Retrofit is a Typesafe HTTP Client first created by Square Inc.

Retrofit's role is to turn your HTTP API into a Java interface:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

In this class we will look at Retrofit and Retrofit Examples with respect to android development. We will see how we can use it to talk to webservices via HTTP in an easy manner.

What are the Requirements for Retrofit?

Retrofit has very generous requirements:

  1. Java 7 and above.
  2. Android 2.3 and above.

How do I Install Retrofit?

Retrofit is a third party HTTP Client library android and java. Hence it needs to be installed into your project.

If you were looking for a networking class that is standard and included in android framework then check HttpURLConnection.

Otherwise Retrofit can be installed in three ways:

1. As a jar.

Basically you download the Retrofit jar and add it to your android studio as a jar library.

For example I used retrofit 2.4.0 which can be downloaded from here.

Otherwise you can check the latest version here.

2. Via maven

Maven, also known as, Apache Maven is a build automation tool used primarily for Java projects.

This gives it two main roles:

  1. Describing how a project is built.
  2. Describing the project's dependencies.

Well we can describe Retrofit as our dependency in a java project.

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
  <version>2.4.0</version>
</dependency>

3. Via Gradle

Gradle is a build system used by android studio.

If you are creating an android project, chances are that you will use this method to install retrofit. This is because you are likely to use Android Studio as it is the official development IDE for android. And android studio utilizes the gradle build system.

In that case you will need to go over to your app level build.gradle and add the following statement in your dependencies DSL:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'

Common Retrofit Interfaces,Classes and Methods.

1. Call

This is a Retrofit interface that represents an invocation of a Retrofit method that sends a request to a webserver and returns a response. As the name suggests it basically represents a HTTP Call you make.

Each call will then yield its own HTTP request and response pair. You able to make multiple calls with the same parameters. However you use clone to achieve that. You can use this to implement polling or to retry a failed call.

When making you HTTP calls, you may make them synchronously or asynchronously. To make synchronous calls you use the execute() method. However to make asynchronous calls you use the enqueue() method.

If you want to cancel any call you use the cancel() method.

Here's it's definition:

public interface Call<T> extends Cloneable

Take note that in this case T represents the type of a successful response body.

2. enqueue()

This is a method that belongs to the Call<T> interface. We talked about that interface representing a HTTP Call you make.

And normally you can make either synchronous or asynchronous call or request. If you want to make an asynchronous call you use this method.

Here's it's definition:

public abstract void enqueue(retrofit2.Callback<T> callback)

This method will then asynchronously send your request and notify callback of its response in case an error occurred talking to the server, creating the request, or processing the response.

Here's a simple usage example:

        Call<List<Spacecraft>> call = myAPIService.getSpacecrafts();
        call.enqueue(new Callback<List<Spacecraft>>() {

            @Override
            public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
                myProgressBar.setVisibility(View.GONE);
                populateRecyclerView(response.body());
            }
            @Override
            public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
                myProgressBar.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

3. Callback

This is an interface defining methods responsible for communicating responses from a server or offline requests.

Here's its definition:

public interface Callback<T>

T in the above represents a successful response body type.

Normally one a single method gets called in response to a given request. That method will be executed using the Retrofit callback executor. If you don't specify any then the following defaults are used:

  1. Android: Callbacks are executed on the application's main (UI) thread.
  2. JVM: Callbacks are executed on the background thread which performed the request.

Here's example usage:

new Callback<List<Spacecraft>>() {

            @Override
            public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
                myProgressBar.setVisibility(View.GONE);
                populateRecyclerView(response.body());
            }
            @Override
            public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
                myProgressBar.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

4. Retrofit

This is a class that is responsible for adapting a Java interface to HTTP calls by using annotations on the declared methods to define how requests are made.

Here's its definition

public final class Retrofit extends Object

To use it you will need to create it's instance. However you do that using the builder and pass your interface to create to generate an implementation. For example:

   Retrofit retrofit = new Retrofit.Builder()
       .baseUrl("https://api.example.com/")
       .addConverterFactory(GsonConverterFactory.create())
       .build();

   MyApi api = retrofit.create(MyApi.class);
   Response<User> user = api.getUser().execute();

Or I can create a simple factory class to return me it's instances:

    static class RetrofitClientInstance {

        private static Retrofit retrofit;
        private static final String BASE_URL = "https://raw.githubusercontent.com/";

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

Then I use that class this way:

        MyAPIService myAPIService = RetrofitClientInstance.getRetrofitInstance().create(MyAPIService.class);

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post