Android Populate Spinner From JSON Using Volley Example

android generate pdf from view, android populate spinner from JSON using Volley

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

Download Source Code For Android Populate Spinner from JSON using Volley

Download Source Code For Spinner_Json_Volley