http://themakeinfo.com/2015/04/retrofit-android-tutorial/
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.
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
1) Overview
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).
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
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 :
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
- package com.makeinfo.flowerpi;
- import android.support.v7.app.ActionBarActivity;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- import com.makeinfo.flowerpi.API.gitapi;
- import com.makeinfo.flowerpi.model.gitmodel;
- import retrofit.Callback;
- import retrofit.RestAdapter;
- import retrofit.RetrofitError;
- import retrofit.client.Response;
- public class MainActivity extends ActionBarActivity {
- Button click;
- TextView tv;
- EditText edit_user;
- ProgressBar pbar;
- String API = "https://api.github.com"; //BASE URL
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- click = (Button) findViewById(R.id.button);
- tv = (TextView) findViewById(R.id.tv);
- edit_user = (EditText) findViewById(R.id.edit);
- pbar = (ProgressBar) findViewById(R.id.pb);
- pbar.setVisibility(View.INVISIBLE);
- click.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- String user = edit_user.getText().toString();
- pbar.setVisibility(View.VISIBLE);
- //Retrofit section start from here...
- RestAdapter restAdapter = new RestAdapter.Builder()
- .setEndpoint(API).build(); //create an adapter for retrofit with base url
- gitapi git = restAdapter.create(gitapi.class); //creating a service for adapter with our GET class
- //Now ,we need to call for response
- //Retrofit using gson for JSON-POJO conversion
- git.getFeed(user,new Callback<gitmodel>() {
- @Override
- public void success(gitmodel gitmodel, Response response) {
- //we get json object from github server to our POJO or model class
- 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
- }
- });
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- //noinspection SimplifiableIfStatement
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- }
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.
ReplyDeleteGoogle App Integration Chennai