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

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 https://androidtutorialpoint.com/api/RetrofitAndroidObjectResponse
JsonArray URL https://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 (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.
1
2
3
4
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

1
2
3
4
5
6
public interface GetAPI {
 
    @GET("/list")
    Model getModel();
 
}

And asynchronous function like this:

Asynchronous in Retrofit 1.9

1
2
3
4
5
6
public interface GetAPI {
 
    @GET("/list")
    void getModel(Callback<Model> cb);
 
}

But now in Retrofit 2.0 you can simply declare:

1
2
3
4
5
public interface GetAPI {
    @GET("/list")
    Call<Model> getModel();
}

Synchronous Call in Retrofit 2.0

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

Asynchronous Call in Retrofit 2.0

1
2
3
4
5
6
7
8
9
10
11
12
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

1
<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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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<list>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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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.

Advertisements
This entry was posted in Android Development. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s