Retrofit Android Get JSON Example Step by Step | Get JSON Object

retrofit android get json, android retrofit listview, android recyclerview retrofit, android spinner example to load json using retrofit, android google map draw path, android google map draw path between current location and destination

Learn today about Retrofit Android Get JSON Example Step by Step.

We will learn how to parse JSON from URL or Server Using Retrofit Library in android.

You will learn how to fetch/retrieve data from MySQL database in android using json, retrofit and PHP.

When you want to interact with remote server such as to get data from server or to send data to remote server, you need to make http calls.

Retro fit is the library which make this task easier and faster.

Web Host Recommendation

If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.

Click this link to see affordable plans.

(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)

Check Final Texts

Below video demonstrate how the outcome of this project will look a like

 

Basics about Retrofit

Square have developed the retrofit library.

Retrofit is the REST client for Java and Android development.

This library makes development tasks easier to get or send the data in the JSON format.

Retrofit uses the OkHttp library for HTTP requests. It also handles the cache operations itself with any coding from app developer.

Generally, developers make custom classes to parse JsonArray or JsonObject separately.

In this tutorial, we will get the JSON response in the string format. Then we can use android’s built in classes like JSONArray and JSONObject to parse the JSON in string format.

So now follow all the below steps of this example.

Step 1. Write Retrofit Dependency

First of all, make a new project in android studio.

Write down the following two lines in the build.gradle(Module:app) file.

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
  • First line will integrate the required classes for retrofit.
  • Second one will get the files for scalar library.

Retrofit will help us to make http calls to the remote web server. While scalar will convert the JSON response in the string format for us.

Give Internet Permission

Add the below line in the AndroidManifest.xml file.

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

This line will allow our project to use the internet of the android device.

Step 2. Making Interface

For making the http call, we need to create one interface.

Make a new JAVA class and give it a name ApiInterface.java

Below is the source code for ApiInterface.java

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {

    String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";

    @GET("json_parsing.php")
    Call<String> getString();

}
  • First string variable holds the path of the URL. This variable do not include the name of the file.
  • I have set the file name in the @GET annotation.

Then we need to define the call function. Name of the function is getString().

Step 3. Making the Model class

Model class will help us to maintain the proper data structure.

Make a new class named RetroModel.java and copy the below source code in it

public class RetroModel {

    private String name, country, city, id;

    public String getid() {
        return id;
    }

    public void setid(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}
  • Our JSON response holds the information like name, country, city, id.
  • So the above class includes the getter and setter methods for all these parameters.

We will use these methods to send and receive data in the MainActivity.java file.

Step 4. Final Modifications

When you created the new project in android studio, you should have two file in the project. activity_main.xml and MainActivity.java

Write the below code structure in activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:text=" below information is fetched from URL With Retrofit"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv"
        android:layout_marginLeft="10dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:textSize="20sp"
        android:textColor="#000" />

</LinearLayout>
  • I have written two textviews in the above file.
  • First textview is static and it is just saying that below information is fetched using retrofit.
  • Second textview will hold the JSON data. We will insert the data in this textview in Main Activity.

Code snippet for MainActivity.java file looks like the below

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.tv);

        getResponse();

    }

    private void getResponse(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        ApiInterface api = retrofit.create(ApiInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeTv(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void writeTv(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<RetroModel> retroModelArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    RetroModel retroModel = new RetroModel();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    retroModel.setid(dataobj.getString("id"));
                    retroModel.setName(dataobj.getString("name"));
                    retroModel.setCountry(dataobj.getString("country"));
                    retroModel.setCity(dataobj.getString("city"));

                    retroModelArrayList.add(retroModel);

                }

                for (int j = 0; j < retroModelArrayList.size(); j++){
                    textView.setText(textView.getText()+ retroModelArrayList.get(j).getid()+ " "+ retroModelArrayList.get(j).getName()
                            + " "+ retroModelArrayList.get(j).getCountry()+ " "+retroModelArrayList.get(j).getCity()+" \n");
                }

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

Reading above source code

In the onCreate() method, compiler will first get the id of the text view.

Then it will call the method getResponse().

getResponse() method looks like the following

 private void getResponse(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        ApiInterface api = retrofit.create(ApiInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeTv(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }
  • First of all, compiler will make the object of the Retrofit class.
  • Here, it will bind the URL using .baseUrl() method.
  • Then it will create the object of the interface ApiInterface. Using this object, it will create new Callback and will run the .enqueue() method.
  • After this much, retrofit have make the http call to the URL and it has get the response.
  • Compiler will read the JSON response in the onResponse() method.

Below line will give us the JSON response in the String format.

String jsonresponse = response.body().toString();
  • Then compiler will call the writeTv(jsonresponse) method. Compiler will pass the string variable which holds the JSON response in the parameter of this method.

Code structure for writeTv(jsonresponse) method is as the below

private void writeTv(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<RetroModel> retroModelArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    RetroModel retroModel = new RetroModel();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    retroModel.setid(dataobj.getString("id"));
                    retroModel.setName(dataobj.getString("name"));
                    retroModel.setCountry(dataobj.getString("country"));
                    retroModel.setCity(dataobj.getString("city"));

                    retroModelArrayList.add(retroModel);

                }

                for (int j = 0; j < retroModelArrayList.size(); j++){
                    textView.setText(textView.getText()+ retroModelArrayList.get(j).getid()+ " "+ retroModelArrayList.get(j).getName()
                            + " "+ retroModelArrayList.get(j).getCountry()+ " "+retroModelArrayList.get(j).getCity()+" \n");
                }

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

For understanding above method, let us first check the JSON data which we have got.

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [
        {
            "id": "1",
            "name": "Roger Federer",
            "country": "Switzerland",
            "city": "Basel"
        },
        {
            "id": "2",
            "name": "Rafael Nadal",
            "country": "Spain",
            "city": "Madrid"
        },
        {
            "id": "3",
            "name": "Novak Djokovic",
            "country": "Serbia",
            "city": "Monaco"
        },
        {
            "id": "4",
            "name": "Andy Murray",
            "country": "United Kingdom",
            "city": "London"
        },
        {
            "id": "5",
            "name": "Maria Sharapova",
            "country": "Russia",
            "city": "Moscow"
        },
        {
            "id": "6",
            "name": "Caroline Wozniacki",
            "country": "Denmark",
            "city": "Odense"
        },
        {
            "id": "7",
            "name": "Eugenie Bouchard",
            "country": "Canada",
            "city": " Montreal"
        },
        {
            "id": "8",
            "name": "Ana Ivanovic",
            "country": "Serbia",
            "city": "Belgrade"
        }
    ]
}
  • First of all, compiler will parse the parent object from the JSON response.
  • Then from this parent object, it will check the value of the “status” field.
  • If it is true, then it will create one arraylist with objects of the RetroModel class, which we have written in the Step 3.
  • Now compiler will create one JSONArray which is represented by the field “data“.
  • After this, it will make one for loop. During every iteration of this for loop, compiler will create the object of the RetroModel class and it will set the data with this object.
  • Then it will add this object into the arraylist.

Now another for loop is there. In this for loop, compiler will set the data in to the text view.

Web Host Recommendation

If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.

Click this link to see affordable plans.

(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)

Download Source Code For retrofit android get json example

Click me Download Json_Parsing_URL_Retrofit Source Code