JSONParsing and HTTPClient in Android

Introduction

 
JSON is an acronym for JavaScript Object Notation. JSON is used for data exchange and is a very condense data exchange format. JSON is used for storing data in files and it is a very easy method to parse data. Android provides support to parse JSON objects and arrays.
 
Advantages of JSON over XML
  • JSON is faster than XML.
  • It uses arrays.
  • JSON is very easy to read and write.
Http Client
 
When we want to send and receive data over the internet then we use HttpClient. The following is the general procedure for using Httpclient.
  • Create the instance of Http Client
  • Tell HttpClient to execute the Method
  • Read the Response
  • Release the connection
  • Deal with the response
Step 1
 
Create a project like this:
 
CreateProjectJsonParsing
 
Step 2
 
Create an XML file and write this:
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  6.     android:paddingRight="@dimen/activity_horizontal_margin"  
  7.     android:paddingTop="@dimen/activity_vertical_margin"  
  8.     android:paddingBottom="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity"  
  10.     android:background="#ddcc12">  
  11.    
  12.   <TextView  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:id="@+id/textView1"  
  16.         android:textStyle="bold"  
  17.          />  
  18.    
  19.     <TextView  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:id="@+id/textView2"  
  23.         android:textStyle="bold"  
  24.         android:layout_marginTop="100dp"  
  25.         />  
  26.   
  27.     <TextView  
  28.         android:layout_width="wrap_content"  
  29.         android:layout_height="wrap_content"  
  30.         android:id="@+id/textView3"  
  31.         android:textStyle="bold"  
  32.         android:layout_marginTop="200dp"  
  33.         />  
  34.   
  35. </RelativeLayout> 
Step 3
 
Create a Java file and write this:
  1. package com.jsonprsing4;  
  2. import android.annotation.TargetApi;  
  3. import android.os.Build;  
  4. import android.os.Bundle;  
  5. import android.app.Activity;  
  6. import android.os.StrictMode;  
  7. import android.util.Log;  
  8. import android.view.Menu;  
  9. import android.widget.ArrayAdapter;  
  10. import android.widget.ListView;  
  11. import android.widget.TextView;  
  12. import org.json.JSONArray;  
  13. import org.json.JSONException;  
  14. import org.json.JSONObject;  
  15. import java.io.IOException;  
  16. import java.util.ArrayList;  
  17.    
  18. public class MainActivity extends Activity {  
  19.    
  20.     TextView textView1,textView2,textView3;  
  21.     String str1,str2;  
  22.     String name1,name2,name3;  
  23.     String experiencePoints1,experiencePoints2,experiencePoints3;  
  24.    
  25.     String vehicleColor,vehicleType,fuel;  
  26.     private static String url = "http://docs.blackberry.com/sampledata.json";  
  27.     @TargetApi(Build.VERSION_CODES.GINGERBREAD)  
  28.     @Override  
  29.     protected void onCreate(Bundle savedInstanceState) {  
  30.         super.onCreate(savedInstanceState);  
  31.         setContentView(R.layout.activity_main);  
  32.         textView1=(TextView)findViewById(R.id.textView1);  
  33.         textView2=(TextView)findViewById(R.id.textView2);  
  34.         textView3=(TextView)findViewById(R.id.textView3);  
  35.         if (android.os.Build.VERSION.SDK_INT > 9) {  
  36.             StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();  
  37.             StrictMode.setThreadPolicy(policy);  
  38.         }  
  39.         try {  
  40.             JsonParser jsonParser=new JsonParser();  
  41.             JSONArray jsonArray=jsonParser.getJSONFromUrl(url);  
  42.             JSONObject jsonObject=jsonArray.getJSONObject(1);  
  43.             vehicleType=jsonObject.getString("vehicleType");  
  44.                  vehicleColor=jsonObject.getString("vehicleColor");  
  45.                  fuel=jsonObject.getString("fuel");  
  46.                  JSONArray jsonArray1=jsonObject.getJSONArray("approvedOperators");  
  47.                      JSONObject jsonObject1=jsonArray1.getJSONObject(0);  
  48.                      name1 = jsonObject1.getString("name");  
  49.                      experiencePoints1=jsonObject1.getString("experiencePoints");  
  50.                     JSONObject jsonObject2=jsonArray1.getJSONObject(1);  
  51.                     name2 = jsonObject2.getString("name");  
  52.                     experiencePoints2=jsonObject2.getString("experiencePoints");  
  53.                   JSONObject jsonObject3=jsonArray1.getJSONObject(2);  
  54.                     name3 = jsonObject3.getString("name");  
  55.                     experiencePoints3=jsonObject3.getString("experiencePoints");  
  56.    
  57.                  String str1="\nvehicleColor: "+vehicleColor+"\nvehicleType: "+vehicleColor+"\nfuel: "+fuel+"\nname: "+name1+"\nexperiencePoints: "+experiencePoints1;  
  58.                  String str2="\nvehicleColor: "+vehicleColor+"\nvehicleType: "+vehicleColor+"\nfuel: "+fuel+"\nname: "+name2+"\nexperiencePoints: "+experiencePoints2;  
  59.                  String str3="\nvehicleColor: "+vehicleColor+"\nvehicleType: "+vehicleColor+"\nfuel: "+fuel+"\nname: "+name3+"\nexperiencePoints: "+experiencePoints3;  
  60.                   textView1.setText(str1);  
  61.                   textView2.setText(str2);  
  62.                   textView3.setText(str3);  
  63.                   /*  array[1]=vehicleColor; 
  64.                     array[2]=vehicleType; 
  65.                     array[3]=fuel; 
  66.                     array[4]=name1; 
  67.                     array[5]=experiencePoints1; 
  68.                     array[6]=name2; 
  69.                     array[7]=experiencePoints2; 
  70.                     array[8]=name3; 
  71.                     array[9]=experiencePoints3;*/  
  72.                    /* arrayList1=new ArrayList(); 
  73.                     arrayList1.add(vehicleType); 
  74.                     arrayList1.add(fuel); 
  75.                     arrayList1.add(vehicleColor); 
  76.                     arrayList1.add(name); 
  77.                     arrayList1.add(experiencePoints);*/  
  78.    
  79.            /* else if(i==1) 
  80.                 { 
  81.                  Log.i("","ADil"); 
  82.                    JSONObject jsonObject=jsonArray.getJSONObject(i); 
  83.                     vehicleType= jsonObject.getString("vehicleType"); 
  84.                     vehicleColor= jsonObject.getString("vehicleColor"); 
  85.                     fuel=jsonObject.getString("fuel"); 
  86.                    JSONArray jsonArray1=jsonObject.getJSONArray("approvedOperator"); 
  87.                     for(int j=0;j<jsonArray.length();j++) 
  88.                     { 
  89.                       JSONObject jsonObject1=jsonArray1.getJSONObject(j); 
  90.                       jsonObject1.getString("name"); 
  91.                       jsonObject1.getString("experienceoperator"); 
  92.                     } 
  93.                     /*arrayList2=new ArrayList(); 
  94.                     arrayList2.add(vehicleType); 
  95.                     arrayList2.add(fuel); 
  96.                     arrayList2.add(vehicleColor); 
  97.                     arrayList2.add(name); 
  98.                     arrayList2.add(experiencePoints);*/  
  99.    
  100.        /*   else if(i==2) 
  101.                 { 
  102.                     Log.i("","Kashif"); 
  103.                 JSONObject jsonObject=jsonArray.getJSONObject(i); 
  104.                     vehicleType=jsonObject.getString("vehicleType"); 
  105.                     vehicleColor=jsonObject.getString("vehicleColor"); 
  106.                     fuel=jsonObject.getString("fuel"); 
  107.                     JSONArray jsonArray1=jsonObject.getJSONArray("approvedOperator"); 
  108.                     for(int j=0;j<jsonArray1.length();j++) 
  109.                     { 
  110.                         JSONObject jsonObject1=jsonArray1.getJSONObject(j); 
  111.                       jsonObject1.getString("name"); 
  112.                       jsonObject1.getString("experienceOperator"); 
  113.                     } 
  114.                    /* arrayList3=new ArrayList(); 
  115.                     arrayList3.add(vehicleType); 
  116.                     arrayList3.add(fuel); 
  117.                     arrayList3.add(vehicleColor); 
  118.                     arrayList3.add(name); 
  119.                     arrayList3.add(experiencePoints);*/  
  120.                 }  
  121.    
  122.        /*arrayList.add(arrayList1); 
  123.        arrayList.add(arrayList2); 
  124.        arrayList.add(arrayList3);*/  
  125.          catch (JSONException e) {  
  126.             e.printStackTrace();  
  127.         }  
  128.     }  
  129.     @Override  
  130.     public boolean onCreateOptionsMenu(Menu menu) {  
  131.         // Inflate the menu; this adds items to the action bar if it is present.  
  132.         getMenuInflater().inflate(R.menu.main, menu);  
  133.         return true;  
  134.     }  
Step 4
 
In this step, you will first create an instance of HttpClient because HttpClient is used when you want to retrieve and send data over the internet. Now you will get all the data using the HttpGet class and by ing the URL to the constructor you will get all the data. Get the response by calling the execute() method of HttpClient.
 
When we want to send and receive data over the internet we use HttpClient. The following is the general procedure for using Httpclient.
  • Create the instance of HttpClient
  • Tell HttpClient to execute the method
  • Read the Response
  • Release the connection
  • Deal with the response
Create a Java file and write this:
  1. package com.jsonprsing4;  
  2. import android.os.AsyncTask;  
  3. import android.util.Log;  
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.StatusLine;  
  7. import org.apache.http.client.ClientProtocolException;  
  8. import org.apache.http.client.HttpClient;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.impl.client.DefaultHttpClient;  
  11. import org.json.JSONArray;  
  12. import org.json.JSONException;  
  13. import java.io.BufferedReader;  
  14. import java.io.IOException;  
  15. import java.io.InputStream;  
  16. import java.io.InputStreamReader;  
  17.    
  18. public class JsonParser extends AsyncTask {  
  19.     static InputStream is = null;  
  20.     static JSONArray jarray = null;  
  21.     static String json = "";  
  22.    
  23.     public JsonParser() {  
  24.     }  
  25.    
  26.     @Override  
  27.     protected Object doInBackground(Object[] params) {  
  28.         return null;  
  29.     }  
  30.    
  31.     public JSONArray getJSONFromUrl(String url) {  
  32.         StringBuilder builder = new StringBuilder();  
  33.         try {  
  34.             HttpClient client = new DefaultHttpClient();  
  35.             HttpGet httpGet = new HttpGet(url);  
  36.             HttpResponse response = client.execute(httpGet);  
  37.             StatusLine statusLine = response.getStatusLine();  
  38.             int statusCode = statusLine.getStatusCode();  
  39.             if (statusCode == 200) {  
  40.                 HttpEntity entity = response.getEntity();  
  41.                 InputStream content = entity.getContent();  
  42.                 BufferedReader reader = new BufferedReader(new InputStreamReader(content));  
  43.                 String line;  
  44.                 while ((line = reader.readLine()) != null) {  
  45.                     builder.append(line);  
  46.                 }  
  47.             } else {  
  48.                 Log.e("Error....""Failed to download file");  
  49.             }  
  50.         } catch (ClientProtocolException e) {  
  51.             e.printStackTrace();  
  52.         } catch (IOException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.         try {  
  56.             jarray = new JSONArray( builder.toString());  
  57.         } catch (JSONException e) {  
  58.             Log.e("JSON Parser""Error parsing data " + e.toString());  
  59.         }  
  60.         return jarray;  
  61.     }  
Step 5
 
Android Manifest.xml file
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.jsonprsing4"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.    
  7.     <uses-sdk  
  8.         android:minSdkVersion="7"  
  9.         android:targetSdkVersion="16" />  
  10.    
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name="com.jsonprsing4.MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.    
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.         </activity>  
  25.    
  26.     </application>  
  27.     <uses-permission android:name="android.permission.INTERNET"/>  
  28. </manifest> 
Step 6
 
Retrieve data through the internet.
 
JsonArrayData