Android Spinner Example to Load JSON Using Retrofit

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

Let us create Android Spinner Example to Load JSON Using Retrofit in this article.

In this tutorial, we will populate android spinner from MySQL database using retrofit and JSON data.

To set the spinner value from JSON using retrofit, we will have to call one web service.

Retrofit will help us to make http call to web service with very fewer lines of code.

We will get the JSON response in string value and we will parse this JSON using scalar library.

Result of this example

Watch the below video which shows the final output of this android spinner retrofit example tutorial.

Step 1. Permission Works

Before everything, make a new project in android studio.

When we want to fetch JSON data from remote server, we need to use internet.

For this purpose add the below line in AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />
  • Internet permission is regular one, which is not much sensitive in terms of privacy of the user.
  • Hence, we do not need to ask for runtime internet permission.

Now in your build.gradle(Module: app) file, add the below couple of lines.

 implementation 'com.squareup.retrofit2:retrofit:2.5.0'
 implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
  • First line will fetch necessary classes to use retrofit in this project.
  • Second line will help us to convert the JSON response into the string format.

Step 2. Drawable file Plus Image

In our spinner, we will use customize dropdown icon.

For this we need one image of dropdown arrow which you can download by clicking the below link

Download arrow Image

  • Add this image to the res->drawable directory.

Now time to create one XML file in the same directory. Give it a name spinner.xml

Write down the below source code in  spinner.xml file

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <layer-list>
        <item>
            <shape android:shape="rectangle">
                <padding
                    android:left="4dp"
                    android:top="4dp"
                    android:right="8dp"
                    android:bottom="4dp"
                    />

                <gradient android:startColor="#00c4c7a9" android:endColor="#00d6dadf" android:angle="270" />
                <stroke android:width="2px" android:color="@color/colorAccent" />
                <corners android:radius="2dp" />
            </shape>
        </item>

        <item>

            <bitmap android:gravity="center|right"
                android:src="@drawable/droparrow"/>
        </item>

    </layer-list>
</item>
</selector>
  • Above file will draw the border to our spinner.
  • The color of the borders will be pink (colorAccent from the colors.xml)

You can change the color of the borders using the below line

 <stroke android:width="2px" android:color="@color/colorAccent" />
  • You can also change the size or width of the border using the above line.

To change the corner radius of the border, you can use below line

 <corners android:radius="2dp" />
  • Increase the above value to get more width of the border.

To set the custom dropdown icon, you need to use the below code lines

 <item>
            <bitmap android:gravity="center|right"
                android:src="@drawable/droparrow"/>
</item>
  • Using gravity, you can set the place where you want to put dropdown arrow. I have put it at center and right.
  • Use src to give reference to the arrow image.

Step 3. Perfect Interface

To write the URL of the web service, we need to make one interface in this example.

Prepare a new JAVA class and call it SpinnerInterface.java

Code structure for SpinnerInterface.java is as the following

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

public interface SpinnerInterface {

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

    @GET("json_parsing.php")
    Call<String> getJSONString();
}
  • A string variable holds the URL of the JSON data.
  • @GET annotation have the name of the file which will give us JSON response.
  • A method getJSONString() will be called from Main class to make the http call.

Step 4. Making Model For Spinner

Create a new class and set the name as SpinnerModel.java

Code snippet for SpinnerModel.java file is as per the following lines

public class SpinnerModel {

    private String name, country, city, imgURL;

    public String getImgURL(){
        return imgURL;
    }

    public void setImgURL(String imgURL){
        this.imgURL = imgURL;
    }

    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 will provide us information like player’s country, name , city and image URL.
  • Thus, this model class includes the separate getter and setter methods for all these types of information.

Step 5. Ending the Spinner

We have reached at the last step of this tutorial. When you have created a new project, you should have two auto generated files : activity_main.xml and MainActivity.java

In the activity_main.xml, write down the below code lines

<?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="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:textSize="20sp"
        android:layout_margin="10dp"
        android:text="Fetching JSON Data with RETROFIT and Populating below spinner with JSON Data"/>

    <Spinner
        android:id="@+id/spCompany"
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp"
        android:layout_marginTop="100dp"
        android:background="@drawable/spinner"
        android:spinnerMode="dropdown"/>

</LinearLayout>
  • This file have two UI widgets. One is Text View and other one is Spinner.
  • Text View is showing that “Spinner is populated from retrofit json data.”
  • Spinner have background properties to make it more attractive.

Now code snippet for MainActivity.java is looking like the following source codes

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
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;
import static android.R.layout.simple_spinner_item;

public class MainActivity extends AppCompatActivity {

    private ArrayList<SpinnerModel> goodModelArrayList;
    private ArrayList<String> playerNames = new ArrayList<String>();
    private Spinner spinner;

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

        spinner = findViewById(R.id.spCompany);
        fetchJSON();

    }

    private void fetchJSON(){

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

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

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

        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();
                        spinJSON(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 spinJSON(String response){

        try {

            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

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

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

                    SpinnerModel spinnerModel = new SpinnerModel();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    spinnerModel.setName(dataobj.getString("name"));
                    spinnerModel.setCountry(dataobj.getString("country"));
                    spinnerModel.setCity(dataobj.getString("city"));
                    spinnerModel.setImgURL(dataobj.getString("imgURL"));

                    goodModelArrayList.add(spinnerModel);

                }

                for (int i = 0; i < goodModelArrayList.size(); i++){
                    playerNames.add(goodModelArrayList.get(i).getName().toString());
                }

                ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, simple_spinner_item, playerNames);
                spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
                spinner.setAdapter(spinnerArrayAdapter);

            }

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

    }

}

Going Deep

Let us show the above source code in details.

  • In the onCreate() method, there is a method named fetchJSON()

Code structure for fetchJSON() methods is like the following

 private void fetchJSON(){

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

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

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

        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();
                        spinJSON(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) {

            }
        });
    }
  • Compiler will first create the object of the Retrofit class.
  • With this object, one method called .baseUrl() is attached which will give the URL to retrofit.
  • After this, compiler will create the object of the SpinnerInterface class. This object will help us to call getJSONString() method.
  • Till now retrofit have make the http call to the web server and when it get the JSON response in string format, it will call onResponse() method.
  • Under onResponse() method, string variable jsonresponse will hold the full JSON data. Then compiler will call spinJSON() method.

Before we understand the spinJSON() method, checkout the JSON reponse below

{
    "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"
        }
    ]
}

Code structure for spinJSON() method is as per the below

 private void spinJSON(String response){

        try {

            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

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

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

                    SpinnerModel spinnerModel = new SpinnerModel();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    spinnerModel.setName(dataobj.getString("name"));
                    spinnerModel.setCountry(dataobj.getString("country"));
                    spinnerModel.setCity(dataobj.getString("city"));
                    spinnerModel.setImgURL(dataobj.getString("imgURL"));

                    goodModelArrayList.add(spinnerModel);

                }

                for (int i = 0; i < goodModelArrayList.size(); i++){
                    playerNames.add(goodModelArrayList.get(i).getName().toString());
                }

                ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, simple_spinner_item, playerNames);
                spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
                spinner.setAdapter(spinnerArrayAdapter);

            }

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

    }
  • First of all, compiler will check the value of the field “status”. If it is “true” then compiler will create an arraylist with the objects of the SpinnerModel class.
  • Then it will parse one json array associated with the field “data”.
  • After this, compiler will iterate one for loop. During this for loop, it will use setter methods if SpinnerModel class to maintain the data structure.
  • Then compiler will create one array adapter and it will attach it with the spinner.

Download Source Code for android spinner example to load json using retrofit

Download Spinner_JSON_Retrofit Source Code