Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Retrofit Android Tutorial : Example of Retrofit 2.0 capturing JSON Array and JSON Object from URL

Retrofit Android Tutorial

Hello Guys. How are you all ? Hope all are doing well. Keep learning and Rocking ;). In this post, we will learn about Retrofit Android. We will see What is Retrofit Android and how it could be useful in place of Volley and AsyncTask.

What is Retrofit Android

Retrofit is a networking library developed by Square through which we can seamlessly capture JSON response from Web. Now we don’t need any JSON Parser to parse the data. Retrofit literally composed of all features required for web services. You don’t need any AsyncTask, HttpurlConnection or JsonParser. I would suggest you to read more about advantages of Retrofit Android here: Retrofit vs Volley and AsyncTask.

I hope now you are very clear about what is retrofit android and why is it better than Volley or AsyncTask.

Note:Volley is developed by Google while Retrofit by Square. We will always be sure that Volley will remain free to use in future but can’t say about Retrofit. So please keep in mind this before using Retrofit in your Android App.

Let’s dive into its functionality. In the following code we will capture data from following URL:

JsonObject URL http://androidtutorialpoint.com/api/RetrofitAndroidObjectResponse
JsonArray URL http://androidtutorialpoint.com/api/RetrofitAndroidArrayResponse

If you copy paste above URL in a browser, you will be able to see JSON data. We will read this data using Retrofit Android 2.0 and print it on Device Screen.



Pre-requisites:

1) Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
2) A real time android device (Smartphone or Tablet) configured with Android Studio. .
3) A basic knowledge of Android lifecycle and different classes & functions used in Android Studio.

In Retrofit Android, we need two classes:

1) POJO or Model Class: This is used to retrieve data from JSON returned by the server. It will just be composed of getter and setter (http://www.androidtutorialpoint.com/tips-tricks/automatic-getters-and-setters-generation-in-android-studio/) methods of the attributes referred in the URL.

2) Interface: As we know, an Interface is a group of methods with empty bodies. All of the methods in an interface are abstract. Here It will be used to manage calls like GET, POST etc. We will refer it to as Service Class.

Creating a New Project and Adding Retrofit 2.0

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have left Activity Name as MainActivity.
  5. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.
  6. To add Retrofit Android to your project add the following dependency in your App’s build.gradle file.
  7. compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.google.code.gson:gson:1.7.2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.okhttp:okhttp:2.4.0'
    

    Note: This is the newest version of Retrofit Android (2.0). In the previous version (Retrofit 1.9) you have to declare a synchronous function like this:

    Synchronous in Retrofit 1.9

     
    public interface GetAPI {
     
        @GET("/list")
        Model getModel();
     
    }
    

    And asynchronous function like this:

    Asynchronous in Retrofit 1.9

     
    public interface GetAPI {
     
        @GET("/list")
        void getModel(Callback cb);
     
    }
    

    But now in Retrofit 2.0 you can simply declare:

     public interface GetAPI {
    
        @GET("/list")
        Call getModel();
    }
    

    Synchronous Call in Retrofit 2.0

     
    Call call = service.getModel();
    Model model = call.execute();
    

    Asynchronous Call in Retrofit 2.0

    Call call = service.getModel();
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Response response) {
            // Get result Model from response.body()
        }
     
        @Override
        public void onFailure(Throwable t) {
     
        }
    });
    

Add Internet Permission

Add the following permission to your AndroidManifest.xml file

AndroidManifest.xml

POJO or Model Class

Make a POJO class with name Student.java and include it at path …/RetrofitAndroid/app/src/main/java/com/androidtutorialpoint/retrofitandroid/Student.java

Student.java

package com.androidtutorialpoint.retrofitandroid;

public class Student {

    //Variables that are in our json
    private int StudentId;
    private String StudentName;
    private String StudentMarks;

    //Getters and setters
    public int getStudentId() {
        return StudentId;
    }

    public void setStudentId(int bookId) {
        this.StudentId = StudentId;
    }

    public String getStudentName() {
        return StudentName;
    }

    public void setStudentName(String name) {
        this.StudentName = StudentName;
    }

    public String getStudentMarks() {
        return StudentMarks;
    }

    public void setStudentMarks(String price) {
        this.StudentMarks = StudentMarks;
    }

}

In the above code, we have just used getters and setters for the details of the student. Captured data from server will be added to this class.

Interface Declaration:

Make two new interfaces with name RetrofitArrayAPI and RetrofitObjectAPI.java at the path: …/RetrofitAndroid/app/src/main/java/com/androidtutorialpoint/retrofitandroid/

RetrofitArrayAPI.java

package com.androidtutorialpoint.retrofitandroid;

import java.util.List;

import retrofit.Call;
import retrofit.http.GET;

public interface RetrofitArrayAPI {

    /*
     * Retrofit get annotation with our URL
     * And our method that will return us details of student.
    */
    @GET("api/RetrofitAndroidArrayResponse")
    Call> getStudentDetails();

}

RetrofitObjectAPI.java

package com.androidtutorialpoint.retrofitandroid;

import java.util.List;

import retrofit.Call;
import retrofit.http.GET;

/**
 * Created by navneet on 4/6/16.
 */
public interface RetrofitObjectAPI {

    /*
     * Retrofit get annotation with our URL
     * And our method that will return us details of student.
    */
    @GET("api/RetrofitAndroidObjectResponse")
    Call getStudentDetails();
}

In the above code @GET is used to call server (corresponding to URL). It is predefined part of retrofit android library. Only end part of URL will be added here. getStudentDetails is method to get Student details and Student is pojo class to store response coming from server. There is one very prominent difference between two interfaces. We are using Call> to get details of Student in case of Array while Call is used for Object.

Build Retrofit

In Retrofit 1.9, GsonConverter was included in the package and was automatically initiated upon RestAdapter (Now Retrofit) creation. As a result, the json result from server would be automatically parsed into accessible object.

But In Retrofit 2.0, GsonConverter is not included in the package. We need to plug a Converter for getting JSON results and include GSON converter as a separate entity in gradle. We did it at the start of tutorial by including compile ‘com.squareup.retrofit:converter-gson:2.0.0-beta2’ in build.gradle.

Now we will make two functions in MainActivity.java, one for Grabbing Array data and other for Object data.

Capturing JSON Object data using Retrofit Android

    void getRetrofitObject() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

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

        Call call = service.getStudentDetails();

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Response response, Retrofit retrofit) {

                try {

                    text_id_1.setText("StudentId  :  " + response.body().getStudentId());
                    text_name_1.setText("StudentName  :  " + response.body().getStudentName());
                    text_marks_1.setText("StudentMarks  : " + response.body().getStudentMarks());

                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());
            }
        });
    }

In the above code we build Retrofit using Retrofit.Builder() and converted JSON data into accessible data object using GsonConverterFactory. You can read more about GSON. After this we passed our interface RetrofitObjectAPI to the retrofit to get details of the student. Now comes the last but most important part i.e. Executing call and Printing data on device screen.
Calls may be executed synchronously with execute(), or asynchronously with enqueue(). enqueue() will Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response. If response comes then onResponse will be automatically called and we will print data using setText. If response doesn’t come out then onFailure will be called and reason of failure will be printed. So Finally our Object response is ready.

Capturing JSON Array using Retrofit Android

void getRetrofitArray() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

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

        Call> call = service.getStudentDetails();

        call.enqueue(new Callback>() {
            @Override
            public void onResponse(Response> response, Retrofit retrofit) {

                try {

                    List StudentData = response.body();

                    for (int i = 0; i 

This is almost similar to Object response. The only difference is that we are using List StudentData to store Array data. Then we are using for loop to print data one by one.
You can see full code inside MainActivity.java.

Layout

You can see layout file. . Here we have added two buttons to select Array data and Object data. If you click on Retrofit Android Array then data from JSON Array will be shown and if you click Retrofit Android Object then data from JSON Object will be shown.



What’s Next?

With the knowledge of how to use Retrofit 2.0 in Android Applications, you can experiment with different API’s available on the internet, parse them and create beautiful android applications. You can see our tutorial of Retrofit Android Example of How to download image from URL and display it on Android device screen. Also you can’t download large chunk of data using Retrofit Android, you have to use DownloadManager for it. You can refer our tutorial on Android Download Manager .

Moreover wanna a work on a project of Retrofit ?? Refer Google Maps Nearby Places API using Retrofit Android.

Stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

You can Download this full code by clicking below:


CodeProject

The post Retrofit Android Tutorial : Example of Retrofit 2.0 capturing JSON Array and JSON Object from URL appeared first on Android Tutorial Point.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Retrofit Android Tutorial : Example of Retrofit 2.0 capturing JSON Array and JSON Object from URL

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×