DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce
  • Architecting Scalable JSON Pipelines: The Power of a Single PySpark Schema

Trending

  • Getting Started With Agentic Workflows in Java and Quarkus
  • 5 Common Security Pitfalls in Serverless Architectures
  • Every Cache Miss Is a Tiny Tax on Your Performance
  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  1. DZone
  2. Data Engineering
  3. Data
  4. How to Populate Spinner in Android With JSON Data [Snippet]

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.

By 
Satish Kanaujiya user avatar
Satish Kanaujiya
·
Nov. 01, 17 · Code Snippet
Likes (6)
Comment
Save
Tweet
Share
80.2K Views

Join the DZone community and get the full member experience.

Join For Free

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 URL. We 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.

JSON Data (computing) Android (robot)

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

Opinions expressed by DZone contributors are their own.

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Advanced Auto Loader Patterns for Large-Scale JSON and Semi-Structured Data
  • From 13,000 to 20,000+ Endpoints: Architecting Forensics for the Remote Workforce
  • Architecting Scalable JSON Pipelines: The Power of a Single PySpark Schema

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook