Wednesday, 10 June 2015

Retrofit Android Tutorial

http://themakeinfo.com/2015/04/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
https://instructure.github.io/blog/2013/12/09/volley-vs-retrofit/
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.

 Introduction

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 : https://api.github.com/users/basil2style
You can search github users details using this demo app :)

GITHUB

Untitled (1)
qr code

1) Overview

Retrofit Classes
themakeinfo.com – 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 
1) Add INTERNET PERMISSION
<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 : https://api.github.com/users/ + “search term”
Our Json Response look like this :
apigithub
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.
gitmodel.java : http://pastebin.com/4xckerN1

6) gitapi.java

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 part.you 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 = "https://api.github.com";
RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL)setEndpoint(API).build(); 
 
 gitapi git = restAdapter.create(gitapi.class);
git.getFeed(user,new Callback<gitmodel>() {
 @Override
 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
 }
@Override
public void failure(RetrofitError error) {
 tv.setText(error.getMessage());
 pbar.setVisibility(View.INVISIBLE); //disable progressbar
 }
 });

Full MainActivty.java Code

  1. package com.makeinfo.flowerpi;
  2.  
  3. import android.support.v7.app.ActionBarActivity;
  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;
  12.  
  13. import com.makeinfo.flowerpi.API.gitapi;
  14. import com.makeinfo.flowerpi.model.gitmodel;
  15.  
  16. import retrofit.Callback;
  17. import retrofit.RestAdapter;
  18. import retrofit.RetrofitError;
  19. import retrofit.client.Response;
  20.  
  21.  
  22. public class MainActivity extends ActionBarActivity {
  23.  
  24.     Button click;
  25.     TextView tv;
  26.     EditText edit_user;
  27.     ProgressBar pbar;
  28.     String API = "https://api.github.com";                        //BASE URL
  29.    
  30.     @Override
  31.     protected void onCreate(Bundle savedInstanceState) {
  32.         super.onCreate(savedInstanceState);
  33.         setContentView(R.layout.activity_main);
  34.  
  35.         click = (Button) findViewById(R.id.button);
  36.         tv = (TextView) findViewById(R.id.tv);
  37.         edit_user = (EditText) findViewById(R.id.edit);
  38.         pbar = (ProgressBar) findViewById(R.id.pb);
  39.         pbar.setVisibility(View.INVISIBLE);
  40.        
  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);
  46.                
  47.                 //Retrofit section start from here...
  48.                 RestAdapter restAdapter = new RestAdapter.Builder()
  49.                         .setEndpoint(API).build();                                        //create an adapter for retrofit with base url
  50.                        
  51.                 gitapi git = restAdapter.create(gitapi.class);                            //creating a service for adapter with our GET class
  52.  
  53.                 //Now ,we need to call for response
  54.                 //Retrofit using gson for JSON-POJO conversion
  55.                
  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
  60.                        
  61.                         tv.setText("Github Name :"+gitmodel.getName()+"\nWebsite :"+gitmodel.getBlog()+"\nCompany Name :"+gitmodel.getCompany());
  62.                        
  63.                         pbar.setVisibility(View.INVISIBLE);                               //disable progressbar
  64.                     }
  65.  
  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.     }
  75.  
  76.  
  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(R.menu.menu_main, menu);
  81.         return true;
  82.     }
  83.  
  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();
  90.  
  91.         //noinspection SimplifiableIfStatement
  92.         if (id == R.id.action_settings) {
  93.             return true;
  94.         }
  95.  
  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

    ReplyDelete