Android parse json into spinner

If you have a JSON string that is stored in a file locally or on a remote server, you might want to parse the JSON string and display result in a Spinner or in a ListView widget. In this Android, I am going to show you how to parse a JSON string stored in a file in the assets directory of the project. The result is populated to a Spinner widget. If you want to parse a JSON string from a remote server into a ListView widget, you read Load mysql data in listview.






The JSON string that will be parsed is shown below. It is stored in a file called countries.json.

[{"cid":"0","cname":"Afghanistan"},{"cid":"1","cname":"Albania"},{"cid":"2","cname":"Australia"},{"cid":"3","cname":"Bahrain"},{"cid":"4","cname":"Belgium"},{"cid":"5","cname":"Cambodia"},{"cid":"6","cname":"Canada"}]

As you already noted from the previous post, in JSON, square brackets ([]) hold an array and curly braces ({}) hold an object. If you look at the JSON string, it is an array that has seven elements. Each element is an object that contains two pairs of key and value. For example, cid and cname are keys and 0 and Afghanistan are values. So to parse the string, you need to create a JSONArray instance with passing the string to it constructor. Then you can use a loop to extract all objects from the array.

Now to have an example application on parsing JSON, in your Android project, you add a Spinner widget to the activity_main.xml file.
<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"  
   android:orientation="vertical"
   tools:context="com.example.inputdialog.MainActivity" >
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

</RelativeLayout>

In the res/layout folder, you also have to create a layout file called spinner_item.xml file. It represents a single item template of the Spinner.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="5dp"
   android:orientation="horizontal"
   >  
<TextView
     android:id="@+id/txt"
     android:layout_width="wrap_content"
     android:layout_height="match_parent"
     android:layout_marginRight="10dp"
       />

</LinearLayout>

In the MainActivity class that hosts the Spinner, you need to read the JSON string from the file, parse it, and add the result to the Spinner.
				
	import android.support.v7.app.ActionBarActivity;
	import android.os.Bundle;
	import android.view.Menu;
	import android.view.MenuItem;
	import android.widget.ArrayAdapter;
	import android.widget.Spinner;
	import org.json.JSONArray;
	import org.json.JSONException;
	import java.io.IOException;
	import java.io.InputStream;
	import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   ArrayList<String> items=getCountries("countries.json");
   Spinner spinner=(Spinner)findViewById(R.id.spinner);
   ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, 
		R.layout.spinner_layout,R.id.txt,items);
   spinner.setAdapter(adapter);	
		}	
private ArrayList<String> getCountries(String fileName){   JSONArray jsonArray=null;   ArrayList<String> cList=new ArrayList<String>();   try {   InputStream is = getResources().getAssets().open(fileName);   int size = is.available();   byte[] data = new byte[size];   is.read(data);   is.close();   String json = new String(data, "UTF-8");   jsonArray=new JSONArray(json);   if (jsonArray != null) {     for (int i = 0; i < jsonArray.length(); i++) {       cList.add(jsonArray.getJSONObject(i).getString("cname"));      }    }   }catch (IOException e){   e.printStackTrace();   }catch (JSONException je){   je.printStackTrace();   }   return cList;   }
}



Android-parse-json-into-spinner

Posted by: Dara | post date: 01-16-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.