Wednesday, August 19, 2015

Android Json Apache Http Client

Android JSON Apache HTTP Client

1) Create New Project

Using Empty Activity template.

2) Edit Layout

2.1) res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

2.2) res/layout/list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
   android:paddingRight="10dp" >
   <!-- Name Label -->
   <!-- Email label -->
   <!-- Mobile number label -->
       android:text="Mobile: "

3) Edit Java Files


package com.notarazi.myapplication;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
   private ProgressDialog pDialog;
   // URL to get contacts JSON
   private String url "";
   // JSON Node names
   private static final String TAG_CONTACTS "contacts";
   private static final String TAG_ID "id";
   private static final String TAG_NAME "name";
   private static final String TAG_EMAIL "email";
   private static final String TAG_ADDRESS "address";
   private static final String TAG_GENDER "gender";
   private static final String TAG_PHONE "phone";
   private static final String TAG_PHONE_MOBILE "mobile";
   private static final String TAG_PHONE_HOME "home";
   private static final String TAG_PHONE_OFFICE "office";
   // contacts JSONArray
   JSONArray contacts null;
   // Hashmap for ListView
   ArrayList<HashMap<String, String>> contactList new ArrayList<HashMap<String, String>>();
   protected void onCreate(Bundle savedInstanceState) {
       new GetContacts().execute();
    * Async task class to get json by making HTTP call
    * */
   private class GetContacts extends AsyncTask<Void, Void, Void> {
       protected void onPreExecute() {
           // Showing progress dialog
           pDialog new ProgressDialog(MainActivity.this);
           pDialog.setMessage("Please wait...");
       protected Void doInBackground(Void... arg0) {
           // Creating service handler class instance
           ServiceHandler sh = new ServiceHandler();
           // Making a request to url and getting response
           String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
           Log.d("Response: ""> " + jsonStr);
           if (jsonStr != null) {
               try {
                   JSONObject jsonObj = new JSONObject(jsonStr);
                   // Getting JSON Array node
                   contacts = jsonObj.getJSONArray(TAG_CONTACTS);
                   // looping through All Contacts
                   for (int i = 0; i < contacts.length(); i++) {
                       JSONObject c = contacts.getJSONObject(i);
                       String id = c.getString(TAG_ID);
                       String name = c.getString(TAG_NAME);
                       String email = c.getString(TAG_EMAIL);
                       String address = c.getString(TAG_ADDRESS);
                       String gender = c.getString(TAG_GENDER);
                       // Phone node is JSON Object
                       JSONObject phone = c.getJSONObject(TAG_PHONE);
                       String mobile = phone.getString(TAG_PHONE_MOBILE);
                       String home = phone.getString(TAG_PHONE_HOME);
                       String office = phone.getString(TAG_PHONE_OFFICE);
                       // tmp hashmap for single contact
                       HashMap<String, String> contact = new HashMap<String, String>();
                       // adding each child node to HashMap key => value
                       contact.put(TAG_ID, id);
                       contact.put(TAG_NAME, name);
                       contact.put(TAG_EMAIL, email);
                       contact.put(TAG_PHONE_MOBILE, mobile);
                       // adding contact to contact list
               } catch (JSONException e) {
           } else {
               Log.e("ServiceHandler""Couldn't get any data from the url");
           return null;
       protected void onPostExecute(Void result) {
           // Dismiss the progress dialog
           if (pDialog.isShowing())
            * Updating parsed JSON data into ListView
            * */
           ListView mListView = (ListView) findViewById(;
           SimpleAdapter adapter;
           adapter = new SimpleAdapter(MainActivity.thiscontactList,
                   R.layout.list_itemnew String[] { TAG_NAMETAG_EMAIL,
                   TAG_PHONE_MOBILE }, new int[] {,
         , });
Refer the variable declaration below...
   ArrayList<HashMap<String, String>> contactList new ArrayList<HashMap<String, String>>();
If you don’t initialize the variable e.g.…
   ArrayList<HashMap<String, String>> contactList; will get the following error…
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference


package com.notarazi.myapplication;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.util.List;
public class ServiceHandler {
   static String response null;
   public final static int GET 1;
   public final static int POST 2;
   public ServiceHandler() {
    * Making service call
    * @url - url to make request
    * @method - http request method
    * */
   public String makeServiceCall(String url, int method) {
       return this.makeServiceCall(url, method, null);
    * Making service call
    * @url - url to make request
    * @method - http request method
    * @params - http request params
    * */
   public String makeServiceCall(String url, int method,
                                 List<NameValuePair> params) {
       try {
           // http client
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpEntity httpEntity = null;
           HttpResponse httpResponse = null;
           // Checking http request method type
           if (method == POST) {
               HttpPost httpPost = new HttpPost(url);
               // adding post params
               if (params != null) {
                   httpPost.setEntity(new UrlEncodedFormEntity(params));
               httpResponse = httpClient.execute(httpPost);
           } else if (method == GET) {
               // appending params to url
               if (params != null) {
                   String paramString = URLEncodedUtils
                           .format(params, "utf-8");
                   url += "?" + paramString;
               HttpGet httpGet = new HttpGet(url);
               httpResponse = httpClient.execute(httpGet);
           httpEntity = httpResponse.getEntity();
           response = EntityUtils.toString(httpEntity);
       } catch (UnsupportedEncodingException e) {
       } catch (ClientProtocolException e) {
       } catch (IOException e) {
       return response;

4) Edit Application Configuration

4.1) Android Manifest

Include permission to use Internet.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
   package="com.notarazi.myapplication" >
   <uses-permission android:name="android.permission.INTERNET" />
       android:theme="@style/AppTheme" >
       <activity android:name=".MainActivity" >
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />

4.2) Build.Gradle (Module:app)

apply plugin''
android {
   compileSdkVersion 23
   buildToolsVersion "23.0.2"
   useLibrary 'org.apache.http.legacy'
   defaultConfig {
       applicationId "com.notarazi.myapplication"
       minSdkVersion 14
       targetSdkVersion 23
       versionCode 1
       versionName "1.0"
   buildTypes {
       release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
dependencies {
   compile fileTree(dir'libs'include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile ''





  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

  2. Great thoughts you got there, believe I may possibly try just some of it throughout my daily life.
    Best Devops online Training
    Online DevOps Certification Course - Gangboard

  3. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Devops Training courses
    python Training in chennai
    Devops Training in Bangalore

  4. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Best Devops Training in pune
    Microsoft azure training in Bangalore
    Power bi training in Chennai

  5. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

  6. I would really like to read some personal experiences like the way, you've explained through the above article. I'm glad for your achievements and would probably like to see much more in the near future. Thanks for share.
    Data Science Training in Chennai
    Data Science training in kalyan nagar
    Data science training in Bangalore
    Data Science training in marathahalli
    Data Science interview questions and answers
    Data science training in bangalore

  7. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience.
    Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in

    selenium training in Bangalore
    selenium training in Marathahalli
    selenium training in Btm layout
    selenium training in Jaya nagar
    selenium training in Electronic city
    selenium training in Kalyan nagar

  8. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.
    I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Java training in Indira nagar
    Java training in Rajaji nagar
    Java training in Marathahalli
    Java training in Btm layout
    Java training in Marathahalli

  9. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.
    Python Online training
    python Course institute in Chennai
    Python Course institute in Bangalore

  10. Nice Post! Thank you for sharing knowledge, it was very good post to update my knowledge and improve my skills. keep blogging.
    Java Training in Electronic City