logo

Android and JSON

JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.
Remember that some URI’s return a JSONObject object while others return a JSONArray. The following coding uses an URI which returns an JSONArray.

We will be using URL/Web Service:

        http://mobisys.in/quicknotify/get_departments.php?company_id=1

We will be getting following JSON:

[{"dept":"Mobile","dept_id":"1"},{"dept":"Web","dept_id":"2"}]

JSON has a reputation for being somewhat hard to read. JSON objects are constructed in a key:value pair format. The object’s elements are separated by commas, and each object is contained within curly braces {}.
An array of objects is contained within square brackets ‘[]’. This is a common approach to transferring a series of rows from a database to an array of objects in which each array element corresponds to a database row, and each property of the object represents a column of data.

Sample Example

So with this tutorial we will connect to a web service that serves JSON objects/ arrays. We will also learn about how to call Json web service through HttpConnection and send the parameters through GET method of HTTP. We will display the Json array fetched from server in the ListView.

Lets create a project named as”com.mobisys.android.FirstJsonExUrl” having activity
FirstJsonExUrlActivity“.

Firstly main.xml will contain:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    >
<Button  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Get Json"
    android:id="@+id/Button01"
    />
  <ListView
   android:id="@+id/lv"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="8dp"
  />  
    
</LinearLayout>

& its code after the click will look like:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      <div style="display:none"></div>   ((Button)findViewById(R.id.Button01)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				
				executeAsyncTask();
				
			}
        });
      
    }

Ofcourse, JSON web-service will be called in background thread as it involves HTTP connection. Also, we will use Hashtable to send the GET parameters in URL. Our HelperHttp class will encode the URL and send GET parameters from Hashtable.

private void executeAsyncTask(){
		  Hashtable<String,String> ht=new Hashtable<String,String>();
		  GetDeptAyncTask async=new GetDeptAyncTask();
		  ht.put("company_id", "1");
		  Hashtable[] ht_array={ht};
		  async.execute(ht_array);
		 }

private class GetDeptAyncTask extends AsyncTask<Hashtable<String,String>,Void,String>{
  		
		  @Override
		  protected String doInBackground(Hashtable<String,String>... params) {
		   Hashtable ht=params[];
		   
		   String json=HelperHttp.getJSONResponseFromURL(BaseUrl+"get_departments.php", ht);
		   if(json!=null) parseJsonString(deptList,json);
		   else{
		    return "Invalid Company Id";
		   }
		   return "SUCCESS";
		  }
		  
		  protected void parseJsonString(ArrayList<DEPT_HOLD> deptList,String json){
			  try {
				   JSONArray array=new JSONArray(json);
				   for(int i=0;i<array.length();i++){
				    JSONObject j=array.getJSONObject(i);
				    DEPT_HOLD d=new DEPT_HOLD();
				    d.dept=j.optString("dept","");
				    d.dept_id=j.optString("dept_id","");
				    deptList.add(d);
				   }
				   
				  } catch (JSONException e) {
				   e.printStackTrace();
				  }
			  
		  } 
		  
		  
		  @Override
		  protected void onPostExecute(String result){
		   
			  if(result=="SUCCESS")
			  {
			   Toast.makeText(FirstJsonExUrlActivity.this, "Success", Toast.LENGTH_SHORT).show();
			   DeptArrayAdapter adapter=new DeptArrayAdapter(FirstJsonExUrlActivity.this,R.id.text1,deptList);
			   ListView listv=(ListView)findViewById(R.id.lv);
			   listv.setAdapter(adapter);
			  }
			  else{}
		  }
		  
		 }
	

&#91;/sourcecode&#93;<br/>

<h2><font color="#0000FF">Parsing JsonArray</font></h2>
To parse String into JsonArray we can have:
<br/>
JSONArray array=new JSONArray(JString);

Extracting the content from JsonObject

Create the JSONObject and extract content using method getJSONObject().

JSONObject j;
j=array.getJSONObject(Jstring);

We can extract its attributes using methods optString()/getString()
optString(): Returns the value mapped by name if it exists. Returns the empty string if no such mapping exists.

getString(): Returns the value mapped by name if it exists

DEPT_HOLD d=new DEPT_HOLD();
d.dept=j.optString("dept","");
d.dept_id=j.optString("dept_id","");

Run the application

Download the source code and APK file

For simplicity we have only mentioned JSON related source code in blog. But if you interested you can download the source code and you can also learn about how to connect to web service through HTTPConnection.
Click here to download the source code

Also you can download APK file
Click here

AUTHOR: Vikas Hiran
5 Comments
  • satheesh

    Good Tutorial…………

    July 4, 2012
  • kuldeep singh

    good tutorial helped alot. lots of thanks.

    December 7, 2012
  • Hy,

    I tested you example but it doesn’t do anything. can you please tell me where is the problem?

    March 1, 2013
  • how to connect php to android if no internet connection??…. is there any middleware that we can use to connect the two???……for static can i use 127.0.0.1??? to connect to my local database?

    June 9, 2014
  • hari

    nice

    November 18, 2015

Leave a Comment

Your email address will not be published.