Android Populate Spinner From JSON Array | Volley, Retrofit, Web Service

gif splash screen, android populate spinner from json

Android Populate Spinner From JSON, Web series using volley, retrofit is today’s tutorial.

Table of Content

1. Android Populate Spinner From JSON Array Web Service

2. Android Populate Spinner From JSON Using Volley Example

3. Android Spinner Example to Load JSON Using Retrofit

1. Android Populate Spinner From JSON Array Web Service

Greetings with Android Populate Spinner From JSON Array and Web Service Tutorial Example.

You will learn how to populate an android spinner using a json web service and MySQL Database in this post.

To display json data in spinner in android, we need to create string arraylist using web service.

First of all, we will retrieve the JSON Data from MySQL using web service.

Then from this JSON data, we will parse the information in string format.

We will store this information in string arraylist and will use them to load the spinner.

See Spinner

So follow the below steps to load or set android spinner value from json array and web service and MySQL Database.

Step 1. JSON Data To Parse

Following is the json data that we will use to populate the spinner.

URL to the web service is: https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [
        {
            "id": "1",
            "name": "Roger Federer",
            "country": "Switzerland",
            "city": "Basel",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/roger.jpg"
        },
        {
            "id": "2",
            "name": "Rafael Nadal",
            "country": "Spain",
            "city": "Madrid",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/nadal.jpg"
        },
        {
            "id": "3",
            "name": "Novak Djokovic",
            "country": "Serbia",
            "city": "Monaco",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/djoko.jpg"
        },
        {
            "id": "4",
            "name": "Andy Murray",
            "country": "United Kingdom",
            "city": "London",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/murray.jpg"
        },
        {
            "id": "5",
            "name": "Maria Sharapova",
            "country": "Russia",
            "city": "Moscow",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/shara.jpg"
        },
        {
            "id": "6",
            "name": "Caroline Wozniacki",
            "country": "Denmark",
            "city": "Odense",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/woz.jpg"
        },
        {
            "id": "7",
            "name": "Eugenie Bouchard",
            "country": "Canada",
            "city": " Montreal",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/bou.png"
        },
        {
            "id": "8",
            "name": "Ana Ivanovic",
            "country": "Serbia",
            "city": "Belgrade",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/iva.jpg"
        }
    ]
}

Step 2. Using Internet

Our app will internet to call the web service.

For this, we need to write Internet Permissions in the AndroidManifest.xml file.

So the code for AndroidManifest.xml looks like the below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.parsaniahardik.spinner_json_old">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 3. Drawable Tasks

We will make our spinner little bit attractive.

For this, we need one image as the dropdown icon.

Click the below link to download the image.

Download arrow Image

After downloading the image, add it to the res->drawable directory.

Now, we need to create a new XML file under res->drawable directory.

Give this file a name like spinner.xml and add the following source code in it.

<?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 borders around the spinner.

Color of the border will be pink.

You can change the color and width of the border by changing the below line.

<stroke android:width="2px" android:color="@color/colorAccent" />

Change the radius of the corners by editing the following

 <corners android:radius="2dp" />

Dropdown icon can be changed with below code structure

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

Step 4. HttpRequest Class

Create a new JAVA class named HttpRequest.java

Copy the the following code snippet in HttpRequest.java file

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Since HttpClient,BasicNameValuePairs, etc...  are deprecated.
 * I've searched for a good alternative, and couldn't find any. Eventually ended up writing my own solution, so I decided to share to those who needs it.
 * Main goals: to make it intuitive, short, clean and reasonable.
 * NOTE methods: .prepare(), preparePost(), withData(map) & withData(string) are build to allow caller to chain in different variations, examples:
 *HttpRequest req=new HttpRequest("http://host:port/path");
 *
 *Example 1: //prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
 *req.preparePost().withData("name=Bubu&age=29").send();
 *
 *Example 2: //prepare http get request,  send to "http://host:port/path" and read server's response as String
 *req.prepare().sendAndReadString();
 *
 *Example 3: //prepare Http Post request and send to "http://host:port/path" with name=Bubu and age=29 and read server's response as JSONObject
 *HashMap<String, String>params=new HashMap<>();
 params.put("name", "Groot");
 params.put("age", "29");
 *req.preparePost().withData(params).sendAndReadJSON();
 */
public class HttpRequest {
    //Supported HttpRequest methods
    public static enum Method{
        POST,PUT,DELETE,GET;
    }
    private URL url;
    private HttpURLConnection con;
    private OutputStream os;
    //After instantiation, when opening connection - IOException can occur
    public HttpRequest(URL url)throws IOException{
        this.url=url;
        con = (HttpURLConnection)this.url.openConnection();
    }
    //Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
    public HttpRequest(String url)throws IOException{ this(new URL(url)); Log.d("parameters", url); }

    /**
     * Sending connection and opening an output stream to server by pre-defined instance variable url
     *
     * @param //isPost boolean - indicates whether this request should be sent in POST method
     * @throws IOException - should be checked by caller
     * */
    private void prepareAll(Method method)throws IOException{
        con.setDoInput(true);
        con.setRequestMethod(method.name());
        if(method== Method.POST||method== Method.PUT){
            con.setDoOutput(true);
            os = con.getOutputStream();
        }
    }
    //prepare request in GET method
    //@return HttpRequest this instance -> for chaining method @see line 22
    public HttpRequest prepare() throws IOException{
        prepareAll(Method.GET);
        return this;
    }
    /**
     * Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
     * HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
     *
     * @param method HttpRequest.Method - nested enum HttpRequest.Method constant
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest prepare(Method method)throws IOException{
        prepareAll(method);
        return this;
    }
    /**
     * Adding request headers (standard format "Key":"Value")
     *
     * @param headers String variadic params in standard format "Key":"Value"
     * @return HttpRequest this instance -> for chaining method @see line 22
     * */
    public HttpRequest withHeaders(String... headers){
        for(int i=0,last=headers.length;i<last;i++) {
            String[]h=headers[i].split("[:]");
            con.setRequestProperty(h[0],h[1]);
        }
        return this;
    }

    /**
     * Writes query to open stream to server
     *
     * @param query String params in format of key1=v1&key2=v2 to open stream to server
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest withData(String query) throws IOException{
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.close();
        return this;
    }
    /**
     * Builds query on format of key1=v1&key2=v2 from given hashMap structure
     * for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
     * for map: {Iam=Groot} -> builds "Iam=Groot"
     *
     * @param params HashMap consists of key-> value pairs to build query from
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest withData(HashMap<String,String> params) throws IOException{
        StringBuilder result=new StringBuilder();
        for(Map.Entry<String,String>entry : params.entrySet()){
            result.append((result.length()>0?"&":"")+entry.getKey()+"="+entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
            Log.d("parameters",entry.getKey()+"  ===>  "+ entry.getValue());
        }
        withData(result.toString());
         return this;
    }
    //When caller only need to send, and don't need String response from server
    public int send() throws IOException{
        return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
    }
    /**
     * Sending request to the server and pass to caller String as it received in response from server
     *
     * @return String printed from server's response
     * @throws IOException - should be checked by caller
     * */
    public String sendAndReadString() throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder response=new StringBuilder();
        for(String line;(line=br.readLine())!=null;)response.append(line+"\n");
        Log.d("ressss",response.toString());
        return response.toString();
     }
    /**
     * Sending request to the server and pass to caller its raw contents in bytes as it received from server.
     *
     * @return byte[] from server's response
     * @throws IOException - should be checked by caller
     * */
    public byte[] sendAndReadBytes() throws IOException{
        byte[] buffer = new byte[8192];
        InputStream is = con.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int bytesRead;(bytesRead=is.read(buffer))>=0;)output.write(buffer, 0, bytesRead);
        return output.toByteArray();
    }
    //JSONObject representation of String response from server
    public JSONObject sendAndReadJSON() throws JSONException, IOException{
        return new JSONObject(sendAndReadString());
    }
}

Methods of above class will help to call the web service with our URL.

Step 5. Model Works

Make another JAVA class and give it a name ModelData.java

Write down the below code structure in ModelData.java file

public class ModelData {

    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 includes the information like name, country city and image url.

This model class have getter and setter method for this information types.

It helps to reduce complexity and data maintenance.

Step 6. Main Activity Works

Your activity_main.xml file should look like the below coding area

<?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"
    tools:context=".MainActivity">

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

I have taken one spinner in this file.

Set the spinner.xml (created in step 3) file as the background of the spinner. It will modify the look and feel of the spinner.

Now in the MainActivity.java file, you should write the following lines

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String jsonURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private final int jsoncode = 1;
    private static ProgressDialog mProgressDialog;
    private ArrayList<ModelData> modelDataArrayList;
    private ArrayList<String> names = 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);

        loadJSON();

    }

    @SuppressLint("StaticFieldLeak")
    private void loadJSON(){

        showSimpleProgressDialog(this, "Loading...","Fetching Json",false);

        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                HashMap<String, String> map=new HashMap<>();
                try {
                    HttpRequest req = new HttpRequest(jsonURL);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss",result);
                onTaskCompleted(result,jsoncode);
            }
        }.execute();
    }

    public void onTaskCompleted(String response, int serviceCode) {
        Log.d("responsejson", response.toString());
        switch (serviceCode) {
            case jsoncode:

                if (isSuccess(response)) {
                    removeSimpleProgressDialog();  //will remove progress dialog

                    modelDataArrayList = parseInfo(response);
                    // Application of the Array to the Spinner

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

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

                }else {
                    Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
                }
        }
    }

    public ArrayList<ModelData> parseInfo(String response) {
        ArrayList<ModelData> tennisModelArrayList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");

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

                    ModelData playersModel = new ModelData();
                    JSONObject dataobj = dataArray.getJSONObject(i);
                    playersModel.setName(dataobj.getString("name"));
                    playersModel.setCountry(dataobj.getString("country"));
                    playersModel.setCity(dataobj.getString("city"));
                    playersModel.setImgURL(dataobj.getString("imgURL"));
                    tennisModelArrayList.add(playersModel);

                }
            }

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

    public boolean isSuccess(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.optString("status").equals("true")) {
                return true;
            } else {

                return false;
            }

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

    public String getErrorCode(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            return jsonObject.getString("message");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "No data";
    }

    public static void removeSimpleProgressDialog() {
        try {
            if (mProgressDialog != null) {
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
            }
        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();

        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void showSimpleProgressDialog(Context context, String title,
                                                String msg, boolean isCancelable) {
        try {
            if (mProgressDialog == null) {
                mProgressDialog = ProgressDialog.show(context, title, msg);
                mProgressDialog.setCancelable(isCancelable);
            }

            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }

        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();
        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Learn above file step by step

See the following source code

 private String jsonURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private final int jsoncode = 1;
    private static ProgressDialog mProgressDialog;
    private ArrayList<ModelData> modelDataArrayList;
    private ArrayList<String> names = new ArrayList<String>();
    private Spinner spinner;

First line is the string that contains the URL to the web service.

Second line is just a integer.

Third one is the object of the ProgressDialog class which we will use to show the progress dialog while fetching the json data.

Fourth line is making an arraylist with the objects of the ModelData class.

Fifth one is making the string arraylist.

Sixth one is the object of the Spinner class.

In onCreate() method, compiler will call the loadJSON() method.

Code block for the loadJSON() method is as the below

 @SuppressLint("StaticFieldLeak")
    private void loadJSON(){

        showSimpleProgressDialog(this, "Loading...","Fetching Json",false);

        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                HashMap<String, String> map=new HashMap<>();
                try {
                    HttpRequest req = new HttpRequest(jsonURL);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss",result);
                onTaskCompleted(result,jsoncode);
            }
        }.execute();
    }

First of all, compiler will show the loading dialog.

Then it will call the web service to fetch the JSON data.

After fetching the JSON, it will call the onTaskCompleted() method.

Code for onTaskCompleted() method is as the below

 public void onTaskCompleted(String response, int serviceCode) {
        Log.d("responsejson", response.toString());
        switch (serviceCode) {
            case jsoncode:

                if (isSuccess(response)) {
                    removeSimpleProgressDialog();  //will remove progress dialog

                    modelDataArrayList = parseInfo(response);
                    // Application of the Array to the Spinner

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

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

                }else {
                    Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
                }
        }
    }

Compiler will populate the modelDataArrayList using parseInfo() method.

Then it will make one for loop, that will add the names of the players in the string arraylist (names).

After this, compiler will set the values of the spinner using this string arraylist (names).

below is the parsInfo() method’s code

 public ArrayList<ModelData> parseInfo(String response) {
        ArrayList<ModelData> tennisModelArrayList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");

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

                    ModelData playersModel = new ModelData();
                    JSONObject dataobj = dataArray.getJSONObject(i);
                    playersModel.setName(dataobj.getString("name"));
                    playersModel.setCountry(dataobj.getString("country"));
                    playersModel.setCity(dataobj.getString("city"));
                    playersModel.setImgURL(dataobj.getString("imgURL"));
                    tennisModelArrayList.add(playersModel);

                }
            }

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

Compiler will first check the status which is the object in the JSON response.

If the status is true then it will parse the JSON array called “data

This json array “data” is having the information.

So compiler will make one for loop to parse the information in every iteration.

Here, it will create the object of the ModelData calss and will assign the information to it.

Then this object is added in the arraylist and at last, it will return this arraylist.





2. Android Populate Spinner From JSON Using Volley Example

Welcome to Android Populate Spinner From JSON Using Volley Example Tutorial.

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

To load the android spinner with json array using volley, we need to call web service.

We will fetch the JSON data from MySQL database and remote server using web service.

JSON array data will be in string format and we will convert them into string array first.

Watch Spinner Volley

Below steps will help you to make android spinner example to load json using volley.

Step 1. JSON Texts

Following is the JSON data, which we will use in this example.

Here is the link to the web service : https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [
        {
            "id": "1",
            "name": "Roger Federer",
            "country": "Switzerland",
            "city": "Basel",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/roger.jpg"
        },
        {
            "id": "2",
            "name": "Rafael Nadal",
            "country": "Spain",
            "city": "Madrid",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/nadal.jpg"
        },
        {
            "id": "3",
            "name": "Novak Djokovic",
            "country": "Serbia",
            "city": "Monaco",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/djoko.jpg"
        },
        {
            "id": "4",
            "name": "Andy Murray",
            "country": "United Kingdom",
            "city": "London",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/murray.jpg"
        },
        {
            "id": "5",
            "name": "Maria Sharapova",
            "country": "Russia",
            "city": "Moscow",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/shara.jpg"
        },
        {
            "id": "6",
            "name": "Caroline Wozniacki",
            "country": "Denmark",
            "city": "Odense",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/woz.jpg"
        },
        {
            "id": "7",
            "name": "Eugenie Bouchard",
            "country": "Canada",
            "city": " Montreal",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/bou.png"
        },
        {
            "id": "8",
            "name": "Ana Ivanovic",
            "country": "Serbia",
            "city": "Belgrade",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/iva.jpg"
        }
    ]
}

Step 2. Gradle and Manifest

Now we will edit the build.gradle (Module :app) file.

Add the below line in build.gradle (Module :app) file.

 implementation 'com.android.volley:volley:1.1.1'

This line will fetch required classes from volley library that we need to use for web service calling.

Now add the following line in the AndroidManifest.xml file

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

Above line is the internet permissions.

This permissions allows us to use the internet from android device.

Step 3. Image and drawable file

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 4.  Class of Model

Time to create the model class which will help to maintain the data in proper manner.

Prepare a new class and give it a name GoodModel.java

Write down the below coding lines in GoodModel.java file

public class GoodModel {

    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;
    }
}

We will get the information like player name, country, city and image url.

Above class includes the getter and setter methods for all the information types.

Step 5. Last Works

Our final task is to edit main files of our project.

In your activity_main.xml file, add the below code

<?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 Volley 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>

One textview and one Spinner is there in above file.

Textview is just for reference. Spinner is the thing to take into consideration.

I have set the spinner.xml file as the background of this spinner.

spinner.xml file will help us to make attractive spinner with borders, corners and custom dropdown icon.

Source code for MainActivtiy.java file is like the below snippet

import android.app.ProgressDialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import static android.R.layout.simple_spinner_item;

public class MainActivity extends AppCompatActivity {

    private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private static ProgressDialog mProgressDialog;
    private ArrayList<GoodModel> goodModelArrayList;
    private ArrayList<String> names = 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);

        retrieveJSON();

    }

    private void retrieveJSON() {

        showSimpleProgressDialog(this, "Loading...","Fetching Json",false);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.d("strrrrr", ">>" + 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++) {

                                    GoodModel playerModel = new GoodModel();
                                    JSONObject dataobj = dataArray.getJSONObject(i);

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

                                    goodModelArrayList.add(playerModel);

                                }

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

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

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        // request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        requestQueue.add(stringRequest);


    }

    public static void removeSimpleProgressDialog() {
        try {
            if (mProgressDialog != null) {
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
            }
        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();

        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void showSimpleProgressDialog(Context context, String title,
                                                String msg, boolean isCancelable) {
        try {
            if (mProgressDialog == null) {
                mProgressDialog = ProgressDialog.show(context, title, msg);
                mProgressDialog.setCancelable(isCancelable);
            }

            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }

        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();
        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

Learning the Main Code

Look at the following source lines

private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private static ProgressDialog mProgressDialog;
    private ArrayList<GoodModel> goodModelArrayList;
    private ArrayList<String> names = new ArrayList<String>();
    private Spinner spinner;

First line is the url which we need to call for the json parsing.

Second line is the object of the ProgressDialog class.

This object will help us to create loading dialog while we are fetching the web service.

Third line is the arraylist with the objects of the GoodModel class.

Fourth line is also an arraylist but with the strings.

Last line is the simple object of the spinner.

Compiler will call the retrieveJSON() method in the onCreate() method.

Code block for retrieveJSON() method is as the below

private void retrieveJSON() {

        showSimpleProgressDialog(this, "Loading...","Fetching Json",false);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.d("strrrrr", ">>" + 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++) {

                                    GoodModel playerModel = new GoodModel();
                                    JSONObject dataobj = dataArray.getJSONObject(i);

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

                                    goodModelArrayList.add(playerModel);

                                }

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

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

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        // request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        requestQueue.add(stringRequest);


    }

Compiler will show the progress dialog first.

Then it will create the object of the StringRequest class.

Here, we will use the URL to the web service.

After getting the JSON data from remote server, compiler will call the onResponse() method.

Here, it will first parse the json and then it will iterate one for loop.

In the every iteration, it will create one object of the GoodModel.java class and then will assign information to this object.

After this for loop, it will create another for loop where it will fill the string array (names).

Then it will populate the spinner using the string array (names).





3. Android Spinner Example to Load JSON Using Retrofit

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 the compiler will create one array adapter and it will attach it with the spinner.