Android Populating Spinner with JSON Tutorial

In this tutorial, you will learn how to populate a spinner with data remotely using a JSON file in your Android application. A spinner displays a dropdown menu with available values, from which the user can select or navigate. We will create a spinner on the main view and populate it with data remotely using a JSON file and on spinner click will show a selectable dropdown menu. On selected dropdown menu will show the selected results below the spinner. So lets begin…

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project JSONSpinnerTutorial.

Application Name : JSONSpinnerTutorial

Project Name : JSONSpinnerTutorial

Package Name : com.androidbegin.jsonspinnertutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.jsonspinnertutorial;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {
	JSONObject jsonobject;
	JSONArray jsonarray;
	ProgressDialog mProgressDialog;
	ArrayList<String> worldlist;
	ArrayList<WorldPopulation> world;

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

		// Download JSON file AsyncTask
		new DownloadJSON().execute();

	}

	// Download JSON file AsyncTask
	private class DownloadJSON extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// Locate the WorldPopulation Class	
			world = new ArrayList<WorldPopulation>();
			// Create an array to populate the spinner 
			worldlist = new ArrayList<String>();
			// JSON file URL address
			jsonobject = JSONfunctions
					.getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

			try {
				// Locate the NodeList name
				jsonarray = jsonobject.getJSONArray("worldpopulation");
				for (int i = 0; i < jsonarray.length(); i++) {
					jsonobject = jsonarray.getJSONObject(i);

					WorldPopulation worldpop = new WorldPopulation();

					worldpop.setRank(jsonobject.optString("rank"));
					worldpop.setCountry(jsonobject.optString("country"));
					worldpop.setPopulation(jsonobject.optString("population"));
					worldpop.setFlag(jsonobject.optString("flag"));
					world.add(worldpop);

					// Populate spinner with country names
					worldlist.add(jsonobject.optString("country"));

				}
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the spinner in activity_main.xml
			Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

			// Spinner adapter
			mySpinner
					.setAdapter(new ArrayAdapter<String>(MainActivity.this,
							android.R.layout.simple_spinner_dropdown_item,
							worldlist));

			// Spinner on item click listener
			mySpinner
					.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int position, long arg3) {
							// TODO Auto-generated method stub
							// Locate the textviews in activity_main.xml
							TextView txtrank = (TextView) findViewById(R.id.rank);
							TextView txtcountry = (TextView) findViewById(R.id.country);
							TextView txtpopulation = (TextView) findViewById(R.id.population);

							// Set the text followed by the position 
							txtrank.setText("Rank : "
									+ world.get(position).getRank());
							txtcountry.setText("Country : "
									+ world.get(position).getCountry());
							txtpopulation.setText("Population : "
									+ world.get(position).getPopulation());
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub
						}
					});
		}
	}

}

In this activity, we have hosted a JSON file in our server and used the JSON functions to retrieve the JSON array and objects from the URL address. We have created an AsyncTask as a background task to load the JSON objects into a string array. Then we populated the spinner with the selected JSON data and on spinner dropdown item click will show the selected data on the textviews.

JSON File Link : http://www.androidbegin.com/tutorial/jsonparsetutorial.txt

Output:

{ // JSON Object
"worldpopulation": // JSON Array Name
	[ // JSON Array
		 { // JSON Object
		 "rank":1,"country":"China",
		 "population":"1,354,040,000",
		 "flag":"http://www.androidbegin.com/tutorial/flag/china.png"
		 }, 

		 { // JSON Object
		 "rank":2,"country":"India",
		 "population":"1,210,193,422",
		 "flag":"http://www.androidbegin.com/tutorial/flag/india.png"
		 }, 

		 { // JSON Object
		 "rank":3,"country":"United States",
		 "population":"315,761,000",
		 "flag":"http://www.androidbegin.com/tutorial/flag/unitedstates.png"
		 }, 

		 { // JSON Object
		 "rank":4,"country":"Indonesia",
		 "population":"237,641,326",
		 "flag":"http://www.androidbegin.com/tutorial/flag/indonesia.png"
		 }, 

		 { // JSON Object
		 "rank":5,"country":"Brazil",
		 "population":"193,946,886",
		 "flag":"http://www.androidbegin.com/tutorial/flag/brazil.png"
		 }, 

		 { // JSON Object
		 "rank":6,"country":"Pakistan",
		 "population":"182,912,000",
		 "flag":"http://www.androidbegin.com/tutorial/flag/pakistan.png"
		 }, 

		 { // JSON Object
		 "rank":7,"country":"Nigeria",
		 "population":"170,901,000",
		 "flag":"http://www.androidbegin.com/tutorial/flag/nigeria.png"
		 }, 

		 { // JSON Object
		 "rank":8,"country":"Bangladesh",
		 "population":"152,518,015",
		 "flag":"http://www.androidbegin.com/tutorial/flag/bangladesh.png"
		 }, 

		 { // JSON Object
		 "rank":9,"country":"Russia",
		 "population":"143,369,806",
		 "flag":"http://www.androidbegin.com/tutorial/flag/russia.png"
		 }, 

		 { // JSON Object
		 "rank":10,"country":"Japan",
		 "population":"127,360,000",
		 "flag":"http://www.androidbegin.com/tutorial/flag/japan.png"
		 } 
	] // JSON Array
} // JSON Object

Next, create an JSON functions class. Go to File > New > Class and name it JSONfunctions.java. Select your package named com.androidbegin.jsonspinnertutorial and click Finish.

Open your JSONfunctions.java and paste the following code.

JSONfunctions.java

package com.androidbegin.jsonspinnertutorial;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

	public static JSONObject getJSONfromURL(String url) {
		InputStream is = null;
		String result = "";
		JSONObject jArray = null;

		// Download JSON data from URL
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		// Convert response to string
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		try {

			jArray = new JSONObject(result);
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}

		return jArray;
	}
}

Next, create an XML graphical layout for the MainActivity. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file activity_main.xml and paste the following code.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

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

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/my_spinner" />

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rank" />

    <TextView
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/country" />

</RelativeLayout>

In your AndroidManifest.xml, we need to declare permissions to allow the application to connect to the Internet. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.jsonspinnertutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

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

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

</manifest>

Output:

JSONSpinnerTutorial ScreenShots

Source Code

JSONSpinnerTutorial (1.1 MiB, 167 downloads)
  • Umar

    Error establishing a database connection

    :/ cant download the project

    • http://www.AndroidBegin.com/ AndroidBegin

      Yea, I’m contacting my hosting account. it seems there are too many users accessing this site. please wait

    • http://www.AndroidBegin.com/ AndroidBegin

      It seems ok now. try downloading it now. thanks

      • Umar

        no its not still :/

        • http://www.AndroidBegin.com/ AndroidBegin

          It seems there are too many connections to the database. Seriously, giving me a headache. :(

          • Umar

            Finally !
            Got it thanks :)

          • http://www.AndroidBegin.com/ AndroidBegin

            Thats nice. Glad you had it. I’m bringing the site down for a quick maintenance. I’ll try to move my database to another location. :)

  • Yulius Ardian Febrianto

    Thanks

  • shruthi

    error occured in world(array declaration)

    • Steph

      me to having a same error

      • http://www.AndroidBegin.com/ AndroidBegin

        I apologize, I left out the JSONfunctions class. Thanks for your comment.

        • Stephen

          its ok.Everything will be fine now.

    • Stephen

      There will be a incomplete coding in these tutorial.they didn’t add JSONFunction class.With the help of Http request only we can connect to the URL.That also they are not included.

  • Steph

    In main activity WorldPopulation cannot be resolved error occured and then Error occured in world

  • shruthi

    i got succefully

    • Stephen

      ok. I am also got a output successfully with the help of stackoverflow

  • http://www.AndroidBegin.com/ AndroidBegin

    I apologize for my mistake, I left out the JSONfunctions class. I’ve just edited this post, should be working fine now.