Retrofit android tutorial

What is Retrofit?

Retrofit is an Android web service client that accelerates the development of android networking applications by removing the boilerplate code. Most of the complicated task like connection, caching, multithreading, etc. are handled internally by retrofit.

Creating a project

Create a new android studio project. Create a default activity.

Installing a retrofit in android studio project

  • Add the following code inside your dependencies{} block of your build.gradle(module: app) file to install Retrofit, Gson dependencies.
  • Click on Sync Now link that appears on top right of your workspace window.

Note: Go to retrofit official documentation and then click Download for getting the latest version of the library.

Adding the necessary permission

We need to add INTERNET permission in AndroidManifest.xml file

Working with an example

Abstract: We will use retrofit to fetch the GMT(Greenwich Mean Time) from the web server and display it in our activity. We will use api.

    1. Go to app>java your package name, right click and then click on New>Java class. Enter ServerTime as the class name. Add the following code.

      Note that @SerializedName() annotation denotes the json key that is used to encode value in server for api
    2. Go to app>java>your package name, right click and then click on New>Package. Enter webservice as a package name.
    3.  Right click on webservice and then click on New>Java Class. Enter Api as a class name. Select kind as Interface from dropd-down menu and then click Ok.
    4. Add the following code to your
    5. Go to your layout file, add the following code.
    6. In your, add the following code.

      In the above code, we are calling the method fetchTime() to retrieve time from the server. When the device received the time, onResponse() method will be called automatically.
    7. Whole code


retrofit example android
retrofit example android

Download the source code.

3 thoughts on “Retrofit android tutorial”

  1. Hi there , you awesome, would you please do a tutorial on how to upload an image to the database and store it in the same directory with the php API files, Thanks

Leave a Reply

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