Pages

Tuesday, August 18, 2015

Json Parsing

Android Json Parsing Example


  • Reference site : www.androidhive.info
  • JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server
1) create ServiceHandler.Java Class for creating request to get json data from URL


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.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class ServiceHandler {
    public static final int GET = 1;
    public static final int POST = 2;
    static String response = null;

    public ServiceHandler() {
    }

    public String makeServiceCall(String Url, int method) {
        return this.makeServiceCall(Url, method, null);
    }

    public String makeServiceCall(String Url, int method, List<NameValuePair> params) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            if (method == POST) {
                HttpPost httpPost = new HttpPost(Url);
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }
                httpResponse = httpClient.execute(httpPost);
            } else if (method == GET) {
                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 (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}

2) Edit MainActivity.java file in your project

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
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 ListActivity {
    public static final String Url = "http://api.androidhive.info/contacts/";
    static final String TAG_CONTACTS = "contacts";
    static final String TAG_ID = "id";
    static final String TAG_NAME = "name";
    static final String TAG_EMAIL = "email";
    static final String TAG_ADDRESS = "address";
    static final String TAG_PHONE = "phone";
    static final String TAG_PHONE_HOME = "home";
    static final String TAG_PHONE_MOBILE = "mobile";
    static final String TAG_PHONE_OFFICE = "office";
    static final String TAG_GENDER = "gender";
    ArrayList<HashMap<String, String>> contactsList;
    JSONArray contacts = null;
    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contactsList = new ArrayList<HashMap<String, String>>();
        lv = getListView();
        new getJsonData().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private class getJsonData extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(Url, ServiceHandler.GET);
            if (jsonStr != null)
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    contacts = jsonObject.getJSONArray(TAG_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 gender = c.getString(TAG_GENDER);
                        String address = c.getString(TAG_ADDRESS);

                        JSONObject phone = c.getJSONObject(TAG_PHONE);
                        String mobile = phone.getString(TAG_PHONE_MOBILE);
                        String office = phone.getString(TAG_PHONE_OFFICE);
                        String home = phone.getString(TAG_PHONE_HOME);

                        HashMap<String, String> contact = new HashMap<String, String>();
                        contact.put(TAG_ID, id);
                        contact.put(TAG_NAME, name);
                        contact.put(TAG_EMAIL, email);
                        contact.put(TAG_PHONE_MOBILE, mobile);
                        contactsList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("Service Handler", "Coulden't get any data from Url");
                }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactsList, R.layout.list_item,
                    new String[]{TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE},
                    new int[]{R.id.name, R.id.email, R.id.phone});
            setListAdapter(adapter);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

3)Add Internet permission to AndroidManifest.xml

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




No comments:

Post a Comment