Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Populate Spinner in Android With JSON Data [Snippet]

DZone's Guide to

How to Populate Spinner in Android With JSON Data [Snippet]

These code snippets will allow you to parse JSON data from a URL into the Spinner drop-down menu in an Android application.

· Mobile Zone
Free Resource

In this tutorial, we will learn about how to populate Spinner in Android from JSON values. Spinner is a basically a drop-down list in Android. Here we are getting JSON data from this URLWe have to parse this data into Spinner.

JSON Data:

{
"success": 1,
"Name": [
{
"Country": "India"
},
{
"Country": "US"
},
{
"Country": "UK"
},
{
"Country": "Australia"
},
{
"Country": "Canada "
}
]
}


activity_main.xml

<?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="com.techiesatish.androidspinner.MainActivity"
android:orientation="vertical"
>


<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/country_Name"
/>

</LinearLayout>

MainActivity.java


public class MainActivity extends AppCompatActivity {
Spinner spinner;
String URL="http://techiesatish.com/demo_api/spinner.php";
ArrayList<String> CountryName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CountryName=new ArrayList<>();
        spinner=(Spinner)findViewById(R.id.country_Name);
        loadSpinnerData(URL);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
             String country=   spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
            Toast.makeText(getApplicationContext(),country,Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // DO Nothing here
            }
        });

    }

    private void loadSpinnerData(String url) {
    RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject=new JSONObject(response);
                    if(jsonObject.getInt("success")==1){
                     JSONArray jsonArray=jsonObject.getJSONArray("Name");
                     for(int i=0;i<jsonArray.length();i++){
                     JSONObject jsonObject1=jsonArray.getJSONObject(i);
                     String country=jsonObject1.getString("Country");
                     CountryName.add(country);
                     }
                    }
                    spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
                }catch (JSONException e){e.printStackTrace();}
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        int socketTimeout = 30000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);
        requestQueue.add(stringRequest);
    }

}

This is all about how to populate Spinner from JSON data.

Topics:
android ,mobile ,mobile app development ,code snippet ,json

Published at DZone with permission of Satish Kanaujiya. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}