Thursday, 3 December 2015

Retrofit 2.0 Android Example | Web Services using Retrofit 2.0

Hello warriors How are you guys ? hope all of you are busy in coding..Today i am going to tell you  How to use Retrofit in AndroidNew born baby of web services or new networking library called Retrofit.


I hope all of you are familier  with older methods to get response from server ..if you are not then don't worry everything is set here for you in Retrofit. But I will suggest you to go and check older methods. lets make a short summary of older methods.In older architecture of web services things were devided in three parts:

  • AsyncTask to do all background task
  • HttpClient or HttpurlConnection to do networking task
  • JsonParser Class to parse data comes from server

But in Retrofit You have nothing to do Everything is automatic.  Its like  a joke but its true buddy.
Everything is set for you in Retrofit. Now Lets implement Retrofit in our code. I am going to make a simple example to fetch data from Weather API and i will show some data of Weather to Text View.

First of all I have created an Simple Architecture of Retrofit Example, I hope you will like it.


Steps are very simple as you can see in above picture. We need 3 Things for Complete Retrofit Architecture.
  • Retrofit
  • An Interface with all networking methods and parameters. i.e, RestInterface
  • POJO class to save data coming from server (known as Getter Setter Class)

So time to start coding. Open your Android studio and create new project with Blank Activity like below image.


We Will need 4 Library for Retrofit working.
  1. Retrofit Library
  2. OKHttp Library
  3. Gson Library
  4. Gson Converter Library
Now we will Add Retrofit library to our project : Visit Retrofit Official Site
  • For Android Studio you just need to paste below line of code under dependency of  build.gradle file.

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

Now we will add Another library called Okhttp to our project
  • For Android Studio you just need to paste below line of code under dependency of  build.gradle file.

compile 'com.squareup.okhttp:okhttp:2.4.0' 

Now we will add two more Library Gson and GsonConverter to build.gradle
  • For Android Studio you just need to paste below line of code under dependency of  build.gradle file.
 
compile 'com.google.code.gson:gson:1.7.2'

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Now Sync your project after adding both library. You can see both library in my build.gradle file in below picture:


And Now we will Add Internet Permission to our Manifest file as you can see in below picture:


Now we will make all POJO of JSON data coming from server in my case i am using a whether API

http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0

You can see JSON data by open this link  CurrentWheatherApi . its looks like below picture.

How to Make POJO class in Retrofit by Most Easiest Way :
  • Visit JsonSchema2pojo.org - This is Official website to Convert JSON Data into POJO class. Just You have to Copy Paste all the Codes.
  • Open JsonSchema2pojo its looks like below picture.


Paste your JSON data in box at left side. check source type JSON and Annotation style Gson. Click on preview and you will see all pojo class are created like below.


You can define class name for callback or by default it is Example.java in my case name of call back class is Model. copy all class and paste into your project I will suggest you to make a Different Package for all POJO class like my project.



Things Related to pojo class are done. Now we will move to our MainActivity. First go to your main.xml file and create some textview to show data. here is my xml file.

Now we will create an Interface for all http methods and parameter so go to your package and create an Interface in my case i have created RestInterface. add below code to interface.

 public interface RestApi {

    @GET("/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0")
    Call<Model> getWheatherReport();
}

Here getWheatherReport is method to get whether report and Model is pojo class to store response coming from server and

             /data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0

is end part of url you can see at starting of post.
Now you are done with interface. everything is approximately done now we will build Retrofit inside MainActivity.java and add GsonConverter for json parsing and after building Retrofit object we wil execute it like below code.

 //Creating Rest Services  
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

      RestApi service = retrofit.create(RestApi.class);

       Call<Model> call = service.getWheatherReport(); 

Now execute Call we have created above like below code.

 //Executing Call 
     call.enqueue(new Callback<Model>() {
    @Override    public void onResponse(Response<Model> response, Retrofit retrofit) {

        try {
            String city = response.body().getName();

            String status = response.body().getWeather().get(0).getDescription();

            String humidity = response.body().getMain().getHumidity().toString();

            String pressure = response.body().getMain().getPressure().toString();

            txt_city.setText("city  :  " + city);
            txt_status.setText("status  :  " + status);
            txt_humidity.setText("humidity  : " + humidity);
            txt_pressure.setText("pressure  :  " + pressure);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override    public void onFailure(Throwable t) {

    }
});
YO we have completed our code dude here is MainActivity.java


http://www.mediafire.com/download/07e05g78phnwqns/RetroFitExample.zip


 Screenshot  of above example:

I hope this example will help you to start with Retrofit if you have any question regarding this post feel free to comment.

0 comments:

Post a Comment