ANDROID x RETROFIT— for ‘beginners’.

DISCLAIMER :
1. I use the term ‘beginners’ very loosely, I’m assuming you are familiar(ideally 100%) with creating android apps using java(or at the very least, creating projects in android studio), AND are knowledgeable on the topic of RESTful API’s as I do not cover these in great detail.
2. The article is not an in-depth Retrofit tutorial.
3. You can skip the article entirely and just download the project
here(with scrutiny and judgement of course).

By the end of the article you would have created a functioning application which uses Retrofit — “A type-safe HTTP client for Android and Java” to create requests to, and handle responses from a REST API.
Specifically, the JSONPlaceHolder’s REST API.
The data will be retrieved from the /users endpoint and be displayed on a very basic RecyclerView.
Sounds simple enough right? Let’s dive right in.

Finished product

Project Initialization

Initialization with Android Studio

As part of the initialization, some minor additions to the module’s build.gradle and the AndroidManifest.xml files are required. These additions are to:

  1. Add the Retrofit library to the projects’ dependencies.
  2. Add network permissions to the android app.

Head to the module’s build.gradle file, add the dependency for Retrofit and its accompanying Gson(A JSON parsing library) converter and then click “Sync Now”.

Look for the “dependencies” header within the /app/build.gradle file

Next, navigate to the AndroidManifest.xml file and add the internet permission to gain network/data access .
<uses-permission android:name=”android.permission.INTERNET” />
This needs to be outside of the <application> </application> tags.

Model

Model Object — a data-centric POJO(Plain old java object) which encapsulates closely related items.

Remember that /users endpoint I mentioned earlier? Take a look at the data it returns.

An array of JSON Objects; the data returned from the REST API

The response is an array of JSON objects, each individual object has the following fields : id, name, username, email, address, etc.
Our model object must therefore reflect these fields in order to use the data they contain (Gson uses model classes to convert JSON data to java objects).
Create a new Java class and call it User.java

The variable names in your model object need to match the fields in the JSON object, If you intend to name the variable differently to what is returned in the JSON object you must use the @SerializedName annotation.

API Interface

Create a java interface called ApiService, this interface will manage the type of REST API calls we intend for Retrofit to make.
There are five built-in annotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource is specified in the annotation.
You will only be using the @GET annotation, with the /users endpoint.

Retrofit turns your HTTP API into a Java interface.

when listUsers() is called, Retrofit’s Call class executes the request and if successful, Gson converts the response into a list of User objects.

APIManager

Create a class called ApiManager

This contains the getService() method, which when called, will build a Retrofit instance using the REST API url.
The Retrofit instance generates an implementation of the ApiService interface(with the /users endpoint), which is then returned.

Interface

UsersViewInterface

public interface UsersViewInterface  {     
void setUpAdapterAndView(List<User> listOfUsers);
}

Serves as the meeting point between the controller and the View(what appears on the screen i.e. the Mainactivity class with RecyclerView).

Controllers

DataCallController

The DataCallController class does the actual Retrofit work, it uses an instance of the ApiManager class to execute the Retrofit Call to the REST API and Gson to parse the response, this is done on the background thread. The response is used to create a list of user objects which is then passed to the view(MainActivity‘s RecyclerView) via the MainController.

MainController

Acts as another layer of abstraction, it takes the list of user objects created by the DataCallController and passes it to the view(MainActivity‘s RecyclerView)

View

MainActivity

The MainActivity class servers as the “View”, it receives the list of users from the MainController, and populates the RecyclerView.
Due to the multiple layer abstractions and separation of concerns, the MainActivity is clean and concise.

That’s it for the Retrofit tutorial, I didn’t get into any UI or layout configuration, but it is all included in the full project on on Github.

--

--

--

The Geeks Shall Inherit The Earth. Software Engineer. Android | iOS.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Lab 4: Sensing: Force sensors and photocells

How to connect a solar panel to a Raspberry Pi

Ktor and Kotlin/Native

Raft logs on Swarm mode

Python in 7 Days — 07/7:Exceptions & How to Handle Then

The Components of a Quality Open Source Project

Making Sense of Environments

Identifying categorical and numerical columns and imputing missing values in a DataFrame using…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Charles E.

Charles E.

The Geeks Shall Inherit The Earth. Software Engineer. Android | iOS.

More from Medium

Beginning Android Development Resources

Disabling animations when running Android instrumented tests

Manage back navigation from notification in android

How To Create Listview — android