Wednesday, 10 June 2015

Retrofit Android Tutorial

retrofit + android

Why I chose Retrofit ?

Before using Retrofit from square, I tried volley (from Google) and AsyncTask. After using retrofit,my works gets more easy.You must read the below topics before jumping into this Tutorial.This is a beginner based project which gives an idea of retrieving from api using Retrofit.
This project is also added to my Github
Volley is a small library compared to Retrofit ,but it is undocumented. Retrofit is developed by Square,also famous for okhttp,picasso..etc(you can find it from here).If you need volley ,then you can from Google Training  or Volley Plus from DWork.


Retrofit is a REST Client for Android and Java by Square.This library is easy learn and has more features.This is beginner friendly compared to other Networking libraries.You can GET,POST,PUT,DELETE  ..etc using this library. You can also use picasso for image loading.Read this before using Picasso or Volley.
Get rid of the Introduction and Lets star the Coding !!!
We are using Github Api for this App :
You can search github users details using this demo app :)


Untitled (1)
qr code

1) Overview

Retrofit Classes – MakeInfo

In Retrofit,we need to create 3 classes.
1) POJO (Plain Old Java Object) or Model Class – The json retrieved from the server is added to this class.
2) Interface : Now we need to create an interface for managing url calls like GET,POST..etc.This is the service class.
3) RestAdapter Class : This is RestClient Class. Gson is used in default for the retrofit.You can use setup your own converter for this purpose like jackson which will describe on later tutorials.

2) Adding Retrofit Library to Project

For Gradle :
compile 'com.squareup.retrofit:retrofit:1.9.0'
Currently,1.9.0 is the latest version.You can get updated version from here
For JAR :
          Download jar

3) Create Android Project

1) Creating New Project in Android Studio is by : File  =>  New Project and fill the descriptions and click Next.
2) Fill the minimum SDK for the project, i use 4.0+ (Retrofit  requires Android 2.3+ orJava 6)
3) Select Blank Activity and then fill out the details Activity Name and Layout Namethen click Finish.
4) For Gradle : You can add Retrofit library by adding it on app =>build.gradle (in project view).
retrofit depend
For Jar : Add jar to app => libs folder and right click on the jar file and click on Add as Library.
5) Also create two packages as API and model.
6) Right Click on API and Click New => Java Class ,then  Name it as gitapi and Kind asInterface.
7) Right Click on Package model and Click New => Java Class,then Name it as gitmodeland Kind as Class
retrofit structure
Project Structure

4) Android Manifest 
<uses-permission android:name="android.permission.INTERNET"/>
Your Manifest will look like :

5) Model Class

First,we need to create POJO or Model class.The Json from server cannot be use directly in Java,so we need to use model class.
For URL structure look like this : + “search term”
Our Json Response look like this :
json object response
This is a JSON Object. If you don’t  know the difference between Json Array and Json Object,please read this
Use jsonschema2pojo for creating the pojo easily.Do not use this for every other Json requests,sometime it gives error. I use Source type as Json and Annotation style asGson,then click on preview. :


1) Now we need url calling using our interface.
@GET(“/users/{user}”),this will call the server.where url is from after the BASE URL.The service  calling url will start with ‘/’ and {user} is the string retrieved from edittext.
@Path(“user”) String user is the string which we get from the edit text.
response from the server is then saved into the Pojo.

  7) RestAdapter

Now,this is the main need to setup the Rest Adapter and the service.
1)  API is the Base URL.
2) We need to create a RestAdapter object with Endpoint(API) and then buid().
3) Create a service for adapter with our gitapi.
4) Call the function for getting the response,Callback is used for async method.We need Callback for both success request and error handling.
5) Our parsed json will be now in POJO. You can call each by calling each item.
 String API = "";
RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL)setEndpoint(API).build(); 
 gitapi git = restAdapter.create(gitapi.class);
git.getFeed(user,new Callback<gitmodel>() {
 public void success(gitmodel gitmodel, Response response) {
tv.setText("Github Name :"+gitmodel.getName()+
"\nWebsite :"+gitmodel.getBlog()+"\nCompany Name :"+gitmodel.getCompany());
pbar.setVisibility(View.INVISIBLE); //disable progressbar
public void failure(RetrofitError error) {
 pbar.setVisibility(View.INVISIBLE); //disable progressbar

Full Code

  1. package com.makeinfo.flowerpi;
  3. import;
  4. import android.os.Bundle;
  5. import android.view.Menu;
  6. import android.view.MenuItem;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.ProgressBar;
  11. import android.widget.TextView;
  13. import com.makeinfo.flowerpi.API.gitapi;
  14. import com.makeinfo.flowerpi.model.gitmodel;
  16. import retrofit.Callback;
  17. import retrofit.RestAdapter;
  18. import retrofit.RetrofitError;
  19. import retrofit.client.Response;
  22. public class MainActivity extends ActionBarActivity {
  24.     Button click;
  25.     TextView tv;
  26.     EditText edit_user;
  27.     ProgressBar pbar;
  28.     String API = "";                        //BASE URL
  30.     @Override
  31.     protected void onCreate(Bundle savedInstanceState) {
  32.         super.onCreate(savedInstanceState);
  33.         setContentView(R.layout.activity_main);
  35.         click = (Button) findViewById(;
  36.         tv = (TextView) findViewById(;
  37.         edit_user = (EditText) findViewById(;
  38.         pbar = (ProgressBar) findViewById(;
  39.         pbar.setVisibility(View.INVISIBLE);
  41.         click.setOnClickListener(new View.OnClickListener() {
  42.             @Override
  43.             public void onClick(View v) {
  44.                 String user = edit_user.getText().toString();
  45.                 pbar.setVisibility(View.VISIBLE);
  47.                 //Retrofit section start from here...
  48.                 RestAdapter restAdapter = new RestAdapter.Builder()
  49.                         .setEndpoint(API).build();                                        //create an adapter for retrofit with base url
  51.                 gitapi git = restAdapter.create(gitapi.class);                            //creating a service for adapter with our GET class
  53.                 //Now ,we need to call for response
  54.                 //Retrofit using gson for JSON-POJO conversion
  56.                 git.getFeed(user,new Callback<gitmodel>() {
  57.                     @Override
  58.                     public void success(gitmodel gitmodel, Response response) {
  59.                         //we get json object from github server to our POJO or model class
  61.                         tv.setText("Github Name :"+gitmodel.getName()+"\nWebsite :"+gitmodel.getBlog()+"\nCompany Name :"+gitmodel.getCompany());
  63.                         pbar.setVisibility(View.INVISIBLE);                               //disable progressbar
  64.                     }
  66.                     @Override
  67.                     public void failure(RetrofitError error) {
  68.                      tv.setText(error.getMessage());
  69.                         pbar.setVisibility(View.INVISIBLE);                               //disable progressbar
  70.                     }
  71.                 });
  72.             }
  73.         });
  74.     }
  77.     @Override
  78.     public boolean onCreateOptionsMenu(Menu menu) {
  79.         // Inflate the menu; this adds items to the action bar if it is present.
  80.         getMenuInflater().inflate(, menu);
  81.         return true;
  82.     }
  84.     @Override
  85.     public boolean onOptionsItemSelected(MenuItem item) {
  86.         // Handle action bar item clicks here. The action bar will
  87.         // automatically handle clicks on the Home/Up button, so long
  88.         // as you specify a parent activity in AndroidManifest.xml.
  89.         int id = item.getItemId();
  91.         //noinspection SimplifiableIfStatement
  92.         if (id == {
  93.             return true;
  94.         }
  96.         return super.onOptionsItemSelected(item);
  97.     }
  98. }

1 comment:

  1. Thanks so much for the comment. I try to put together my learning and experiece in terms of blog and feel great if this helps others.

    Google App Integration Chennai