Retrofit 2.0 tutorial with sample application

Retrofit is an HTTP client library in Android and Java. It has great performance compares to AsyncTask and other android networking libraries. Retrofit 2.0 has been released a few months back with a major update. In this tutorial, I am going to talk about how to create a simple REST client in Android that communicates with REST endpoint to perform the READ and WRITE operations. This tutorial is intended for retrofit 2.0 beginner who is using retrofit for the first time and getting their hand dirty with retrofit 2.0.

The overview of application that we are creating is as follows. The application has two main components 1) REST client in Android 2) REST server in Node.js. We will focus on REST client as this writing is for retrofit which is client library. We will create REST endpoints that create and list User. A user has two properties., username and name. The program  (Client) has two methods; one for creating a user and other for listing all the users. Final android application has two fragments in pager view, one has an interface for creating a new user and another for listing the user. In the backend, the program uses Mongodb as a database.

Getting Started

First of all, you need a couple of libraries to get started. Insert the following dependencies in your gradle file.

As you can see, besides retrofit we are going to use gson converter. Gson convertor converts JSON into Java Object and vice-versa.  You can use another converter such as jackson if you like.

Model

Each user in the JSON maps to the User model. As the JSON contains the only username and name keys, User model has these two properties.

API service

Service declaration converts HTTP API into Java interfaces.  This interface calls the HTTP web services. Retrofit 2.0 introduced a new class Call same as Okhttp. Call encapsulates single request/response interaction, it knows about serialization and de-serialisation. It takes the HTTP response and turns it into list of Users (in our case).  One good thing about Call is it actually separates request creation from response handling. Here is our implementation of service declaration

The first call creates the POST request to the REST endpoint that creates new user according to the user object provided as a parameter. @Body denotes that the parameter provided after it acts as the request body of post request.  There are other kinds of annotations available to use as a parameter. For example, to create a dynamic URL, you could use @Path annotation. Here is the list of some of the annotations and their use cases.

@Query – Creates dynamic query string

This can be called in the following way – detail will be discussed later

@QueryMap – Same as @Query except key and value can be supplied a map.

@Path – Dynamically replace the path

@FormUrlEncoded – Sends form encoded data

Other annotations include @Header, @FieldMap, @Multipart, @Headers etc.

Rest Client

So far we created User model and declare the interface to communicate with HTTP using HTTP Verbs GET and POST. Now lets write code that calls these interfaces asynchronously.

Here callbacks are used to make the code asynchronous. There is equivalent synchronous version for calling the interface methods but here I am using asynchronous methods because android doesn’t allows network operation in its main thread. Callback class has two methods onResponse and onFailure. If the request is successful, onResponse method is called with response encapsulated in Response type. Response class has methods that give main body and other various metadata related to the request and response. The Class looks like as follows

Call.enqueue method enqueues the current request in asynchronous call queue. There is corresponding version in synchronous version Call.execute. I want to point out one possible exception when you try to execute or enqueue the request twice using same call object. For example

Server Side

The server side code is written in Node.js. As this tutorial is for client part only. I simply show you the code that connects to mongodb, create user and save to the db and list all the user from db.

Now we came at the end of our tutorial. You can access complete code of both client and server in github repository.

SHARE Retrofit 2.0 tutorial with sample application

You may also like...

5 Responses

  1. sahi ho k .. keto le garcha 🙂 (y)

  2. ashkira says:

    I am getting error at callback.resultReady(shops);
    as follows
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.bookhaircut.externals.RestClient$ResultReadyCallback.resultReady(java.util.List)' on a null object reference

  3. ashkira says:

    Line 38 in RestClient at return users;
    users = null

    can you help ?

  4. Romina ([email protected]) says:

    This is a asynchronous call, so expect a result in a "synchronous" way is not correct. You can take a look to this: http://stackoverflow.com/questions/34184088/how-can-i-return-value-from-function-onresponse-of-retrofit

  5. Youa are probably not assignin the callback anywhere

Leave a Reply

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

Share