Main navigation

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

adsense

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 (https://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<Model> cb);
     
    }
    

    But now in Retrofit 2.0 you can simply declare:

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

    Synchronous Call in Retrofit 2.0

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

    Asynchronous Call in Retrofit 2.0

    Call<Model> call = service.getModel();
    call.enqueue(new Callback<Model>() {
        @Override
        public void onResponse(Response<Model> 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

<uses-permission android:name="android.permission.INTERNET" />

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<List<Student>> 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<Student> 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<Student> call = service.getStudentDetails();

        call.enqueue(new Callback<Student>() {
            @Override
            public void onResponse(Response<Student> 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<List<Student>> call = service.getStudentDetails();

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

                try {

                    List<Student> StudentData = response.body();

                    for (int i = 0; i < StudentData.size(); i++) {

                        if (i == 0) {
                            text_id_1.setText("StudentId  :  " + StudentData.get(i).getStudentId());
                            text_name_1.setText("StudentName  :  " + StudentData.get(i).getStudentName());
                            text_marks_1.setText("StudentMarks  : " + StudentData.get(i).getStudentMarks());
                        } else if (i == 1) {
                            text_id_2.setText("StudentId  :  " + StudentData.get(i).getStudentId());
                            text_name_2.setText("StudentName  :  " + StudentData.get(i).getStudentName());
                            text_marks_2.setText("StudentMarks  : " + StudentData.get(i).getStudentMarks());
                        }
                    }


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

            }

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

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:

Android Tutorial Point Download Now



Reader Interactions

Comments

  1. can u please share the tutorial on how to post the parameters ans also how to load data in spinner by using retrofit library

    • Hi Suganya,

      Yes we will surely post a tutorial of your requirement. Can you please explain in somewhat more details about the project you want?? It will be best if you could give an example 🙂

      Regards,
      Android Tutorial Point

  2. hi,thanks for a reply..For example,if we have a student registration form it consist a list of university & list of city details and also consist various fields like gender info how we post those parameters by using retrofit..And also i request u to post more example by using retrofit library..

  3. Hello,
    I keep getting this error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

    • Hi Yongama,

      This generally happen when you try to grab data from an array while expected is object. I would suggest you to download this project and take difference. One of the possible reason could be, you are providing wrong URL in retrofit interface. All the Best!!

  4. In starting of this article, I couldn’t understand your points. But after reading two times I found it was worth reading for me.

  5. I think I read 2nd or 3rd article on android retrofit on android tutorial point and all are up to the mark, well written, step by step with extra knowledge.

  6. Your every articles are awesome and I would say this blog will be become one of the best blog in android niche for sure.

  7. I keep getting this error in my code –
    java.lang.NullPointerException: Attempt to invoke interface method ‘int java.util.List.size()’ on a null object reference
    11-15 15:28:40.883 29807-29807/com.yng.retrofitexample W/System.err: at com.yng.retrofitexample.MainActivity$3.onResponse(MainActivity.java:85)

    The JSON response is being returned, and yet the arraylist size is zero ?

  8. Hi! This is my first comment here so I just wanted to give
    a quick shout out and tell you I truly enjoy reading through your articles.
    Can you suggest any other blogs/websites/forums that deal with the same subjects?
    Appreciate it!

  9. Every weekend i used to go to see this site, because i wish for enjoyment,
    as this this site conations really pleasant funny material too.

  10. I have recently started a site, the information you provide on this web site has helped me tremendously. Thanks for all of your time & work.

  11. Can you share A tutorial on how to fetch data from objects within objects (more like a class hierarchy and extracting data from the innermost class)

  12. I create a API with java servlet. But when i call it showing a err

    javax.net.ssl.SSLHandshakeException: Handshake failed

    My son response like this
    [{“StudentName”:”Enamul”,”StudentMarks”:”98″,”StudentId”:”1″},{“StudentName”:”Enamul”,”StudentMarks”:”92″,”StudentId”:”2″}]

    please help…

  13. My partner and I stumbled over here by a different web page and thought I might as well check things out.
    I like what I see so now i am following you. Look forward
    to finding out about your web page again.

  14. Magnificent web site. Plenty of useful information here.
    I’m sebding it to a few friends anss additionally sharing in delicious.
    And naturally, thank you in your effort!

    • Has anyone done this using the latest RETROFIT 2 library? I can’t get the Call.enqueue code to be executed using the 2.0 version. Any help is appreciated.

  15. Do you have a working tutorial using RETROFIT 2 ? when I applied the above code using the following libraries since these seem to the the latest , call.enqueue code is not executed. Any help is appreciated.

    compile ‘com.android.support:appcompat-v7:24.2.1’
    compile ‘com.android.support:design:24.2.1’
    compile ‘com.google.code.gson:gson:2.6.2’
    compile ‘com.squareup.retrofit2:retrofit:2.0.2’
    compile ‘com.squareup.retrofit2:converter-gson:2.0.2’

  16. Hi, can u help me, i have an error, like

    error: missing method body, or declare abstract, this error show at getStudentDetails();

  17. I had trouble parsing the JSON array, since of a error in the JSON. There is an extra comma at the end of the second object, which should not be there.

    Becausea of that I had to use setlenient on the GsonConverterFactory, which on its turn created an third null object in onResponse.

  18. Cn u Plz tell me how to retrieve data from php file using retrofit2. i am searching for php script demoof this

Leave a Reply

Advertisment ad adsense adlogger