Thursday, 5 July 2012

Sphinx Search Optimization

Sphinx search is an alternative of performing search in mysql .
From my experience sphinx will provide you a great deal of performance .
For Details http://sphinxsearch.com

This Page is about the optimization that i had done and will boost your performance

* Caching (Use Memcache)
sphinx directly does not support caching. An alternative is to use memcache. 
Based on your website requirements , say i fetch records of 1st 10 pages  and store records in memcache. So when user uses pagination then there is no need to peform a search operation , rather we can fetch records directly from memcache

* Use Of Multiquery / faceted searching
Multi-queries, or query batches, let you send multiple queries to Sphinx in one go.Two API methods that implement multi-query mechanism are AddQuery() and RunQueries(). 


Why To Use:
1. decrease in network roundtrips. 
2. automatic internal optimizations.
3. for new version performance will always increase.


Sequential Code
$cl->SetGroupBy('grouping1', SPH_GROUPBY_ATTR,"@count desc");
$cl->AddQuery ('textToSearch_OPTINAL','IndexName');
$res=$cl->RunQueries();

$cl->SetGroupBy('grouping2', SPH_GROUPBY_ATTR,"@count desc");
$cl->AddQuery ('textToSearch_OPTINAL','IndexName');
$res=$cl->RunQueries();

$cl->SetGroupBy('grouping3', SPH_GROUPBY_ATTR,"@count desc");
$cl->AddQuery ('textToSearch_OPTINAL','IndexName');
$res=$cl->RunQueries();

can be optimized by Multiquery
$cl->SetGroupBy('grouping1', SPH_GROUPBY_ATTR,"@count desc");
$cl->SetGroupBy('grouping2', SPH_GROUPBY_ATTR,"@count desc");
$cl->SetGroupBy('grouping3', SPH_GROUPBY_ATTR,"@count desc");
$cl->AddQuery ('textToSearch_OPTINAL','IndexName');
$res=$cl->RunQueries();

* Avoid use of setSelect('limitedcolumns)
setSelect(*) is much faster than setSelect('limitedcolumns)
Reason:
You have a bucket of colored marbels.If I ask you to pass me all (the *), then you just pass me the bucket.But if I ask you to pass me only the red and yellow ones, it takes you time, because you
have to pick out the right ones, and put them in a new bucket.
Smaller bucket (ie less network bandwidth), but takes longer (processing)




* Use Of SphinxQL (for large in/not-in queries)

client end computations are very high specially when a lot of values are being sent
in a IN or NOT IN clause because for every value it converts it into some binary format
using pack function and then sends to the sphinx server. This causes high load on our web
server because we have queries wherein we show online users within a search criteria and
sometimes online users are around 15k-20k.

example:  normal use of api is slow and cpu utilization consuming

for($i=100;$i<20000;$i++) {        $x[]=$i; }

$cl->SetFilter('PROFILEID',$x,TRUE);
use of sphinxQL will give cpu utilization improvement by 10 times

Distributed searching
To scale well, Sphinx has distributed searching capabilities. Distributed searching is useful to improve query latency (ie. search time) and throughput (ie. max queries/sec) in multi-server, multi-CPU or multi-core environments. This is essential for applications which need to search through huge amounts data (ie. billions of records and terabytes of text).

* Explore sphinx.conf
1. mem_limit                       = 32M (default allocation)
change it to around 2048MB based on your usage.

View Documents online without signing up (Open Source):



  1. Google Docs Viewer:

    Google Docs is one of the most popular cloud based document editor and this is very easy tool to view documents online by using embedded code.
    Ex:  


    <iframe src=”http://docs.google.com/gview?url='Document_url'”

    style=”width:600px; height:400px;” frameborder=”1”>

    </iframe>

    OR

    <iframe src=”http://docs.google.com/viewer?url='Document_url'”
    style=”width:600px; height:400px;” frameborder=”1”>

    </iframe>
    Supported Formats: PDF, XLS, XLSX, DOC, DOCX, PPT, PPTX, PSD, TTF,                                     SVG, XPS

    RND Result: PDF, DOC, PPT, XLS, XLSX, TTF, XPS -Working

    DOCX, PPTX -Not working 


2.  Zoho Document Viewer:

  1. Zoho also a leader in providing web based documents and spreadsheets editing functionalities
    also has a very handy Zoho document viewer.

    This viewer is also same Google docs viewer. Zoho docs also gives an option for embedding

    the document via an iframe code.

    Ex: <iframe src="https://viewer.zoho.com/api/urlview.do?url='document_url'" style="width:600px; height:400px;" frameborder="1"></iframe>

    Supported Formats: Microsoft Office - doc, docx, xls, xlsx, ppt, pptx, pps;

    OpenDocument - odt, ods, odp; OpenOffice:sxw, sxc, sxi;

    Other Formats - wpd, pdf, rtf, txt, html, csv, tsv .

    RND Result: Still not working this API

    Error: Error occurred. Please try again.


3. View Docs online Viewer:

View Docs Online has a cool interface for viewing documents. The flash based interface

has almost all useful features like zooming, selecting text and viewing pages as tiles.

View Docs Offline also gives you an embed code for embedding to your website or blog.

Ex: <iframe src="http://www.viewdocsonline.com/embed/<'DocumentURL'>"

frameborder="0" width="600" height="500"> </iframe>


Supported Formats: Microsoft Office – DOC, DOCX, PPT, PPTX, PPS, XLS, XLSX.

PDF – PDF, PS.

Open office - ODT, ODP, SXI.

Text – TXT, RTF.



4.DocsPal Viewer:

DocsPal has an added feature of converting the documents from one format to another.

It has a very beautiful interface and you’ll be given two options at the beginning,

asking you to either convert or just view a document. Upload your file or give its URL and

view it on the fly. The file format converter is also very impressive and gives good results.

Comment: This viewer has excellent options for viewing and converting all

documents formats. And also given option for viewing

videos/audio/images.




5.Vuzit Viewer:

Web based(online) document viewer. Does't support embed url.



6. Samurajdata Viewer:

           This is a very simple document viewer which also allows viewing a document on the internet via its URL .

Open Source Api.
Supported Formats: Only PDF, Doc,Docx, PostScript.


  1. Scribd Viewer:
This is also Online document viewer.


8.  Box viewer:

This is also online document viewer with Embedded option.

Ex: <embed src="https://boxmarketing.box.net/embed/'DocumentURL'" width="466"
height="400" wmode="opaque" type="application/x-shockwave-flash"
allowFullScreen="true" allowScriptAccess="always" >

Supported Formats: Microsoft Office – DOC, DOCX, PPT, PPTX, PPS, XLS, XLSX.
PDF – PDF, PS.
Open office - ODT, ODP, SXI.
Text – TXT, RTF.


                                                                         -PAVANKUMAR JOSHI

Embedding All Online Videos on Your Web Page or Blog


CREATE OWN DYNAMIC TREE VIEW USING JAVA


Embedding YouTube Videos on Your Web Page or Blog


Android SQLite Database Tutorial


Android provides several ways to store user and app data. SQLite is one way of storing user data. SQLite is a very light weight database which comes with Android OS. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations.

Download Code
In this tutorial I am taking an example of storing user contacts in SQLite database. I am using a table called Contacts to store user contacts. This table contains three columns id (INT), name (TEXT), phone_number(TEXT).
Following is the structure of contacts table.
Sqlite contacts table
Writing Contact Class
Before you go further you need to write your Contact class with all getter and setter methods to maintain single contact as an object.
Contact.java
package com.androidhive.androidsqlite;
public class Contact {
    //private variables
    int _id;
    String _name;
    String _phone_number;
    // Empty constructor
    public Contact(){
    }
    // constructor
    public Contact(int id, String name, String _phone_number){
        this._id = id;
        this._name = name;
        this._phone_number = _phone_number;
    }
    // constructor
    public Contact(String name, String _phone_number){
        this._name = name;
        this._phone_number = _phone_number;
    }
    // getting ID
    public int getID(){
        return this._id;
    }
    // setting id
    public void setID(int id){
        this._id = id;
    }
    // getting name
    public String getName(){
        return this._name;
    }
    // setting name
    public void setName(String name){
        this._name = name;
    }
    // getting phone number
    public String getPhoneNumber(){
        return this._phone_number;
    }
    // setting phone number
    public void setPhoneNumber(String phone_number){
        this._phone_number = phone_number;
    }
}
Writing SQLite Database Handler Class
  We need to write our own class to handle all database CRUD(Create, Read, Update and Delete) operations.
1. Create a new project by going to File ⇒ New Android Project.
2. Once the project is created, create a new class in your project src directory and name it as DatabaseHandler.java ( Right Click on src/package ⇒ New ⇒ Class)
3. Now extend your DatabaseHandler.java class from SQLiteOpenHelper.
public class DatabaseHandler extends SQLiteOpenHelper {
4. After extending your class from SQLiteOpenHelper you need to override two methods onCreate() and onUpgrage()
onCreate() – These is where we need to write create table statements. This is called when database is created.
onUpgrade() – This method is called when database is upgraded like modifying the table structure, adding constraints to database etc.,
public class DatabaseHandler extends SQLiteOpenHelper {
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
        // Create tables again
        onCreate(db);
    }
⇒All CRUD Operations (Create, Read, Update and Delete)
Now we need to write methods for handling all database read and write operations. Here we are implementing following methods for our contacts table.
// Adding new contact
public void addContact(Contact contact) {}
// Getting single contact
public Contact getContact(int id) {}
// Getting All Contacts
public List<Contact> getAllContacts() {}
// Getting contacts Count
public int getContactsCount() {}
// Updating single contact
public int updateContact(Contact contact) {}
// Deleting single contact
public void deleteContact(Contact contact) {}
⇒Inserting new Record
The addContact() method accepts Contact object as parameter. We need to build ContentValues parameters using Contact object. Once we inserted data in database we need to close the database connection.
addContact()
    // Adding new contact
public void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}
⇒Reading Row(s)
The following method getContact() will read single contact row. It accepts id as parameter and will return the matched row from the database.
getContact()
    // Getting single contact
public Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();
    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    // return contact
    return contact;
}
getAllContacts() will return all contacts from database in array list format of Contact class type. You need to write a for loop to go through each contact.
getAllContacts()
    // Getting All Contacts
 public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    return contactList;
}
getContactsCount() will return total number of contacts in SQLite database.
getContactsCount()
// Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }
⇒Updating Record
updateContact() will update single contact in database. This method accepts Contact class object as parameter.
updateContact()
    // Updating single contact
public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());
    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}
⇒Deleting Record
deleteContact() will delete single contact from database.
deleteContact()
    // Deleting single contact
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}
Complete DatabaseHandler.java Code:
DatabaseHandler.java
package com.androidhive.androidsqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
        // Create tables again
        onCreate(db);
    }
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }
    // Getting single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }
    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
        // return contact list
        return contactList;
    }
    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }
    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }
    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        // return count
        return cursor.getCount();
    }
}
Usage:
AndroidSQLiteTutorialActivity
package com.androidhive.androidsqlite;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AndroidSQLiteTutorialActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DatabaseHandler db = new DatabaseHandler(this);
        /**
         * CRUD Operations
         * */
        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("Ravi", "9100000000"));
        db.addContact(new Contact("Srinivas", "9199999999"));
        db.addContact(new Contact("Tommy", "9522222222"));
        db.addContact(new Contact("Karthik", "9533333333"));
        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        List<Contact> contacts = db.getAllContacts();      
        for (Contact cn : contacts) {
            String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
                // Writing Contacts to log
        Log.d("Name: ", log);
    }
    }
}
Android Log Cat Report:
I am writing output to Log report. You can see your log report by going to Windows ⇒ Show View ⇒ Other.. ⇒ Android ⇒ Log Cat.
Android Log Cat
Android Log Cat
Android Output log report

Android JSON Parsing Tutorial


JSON is the best alternative to XML for storing data in files. It is easy to parse and access data stored in JSON format. Previously i explained parsing XML and today i am going to discuess parsing JSON data with an example.

The JSON Structure
I am taking an example of following JSON which will give you list of contacts and each contact will have details like name, email, address, phone number ertc,. You can get this JSON data by accessing http://api.androidhive.info/contacts/
{
    "contacts": [
        {
                "id": "c200",
                "name": "Ravi Tamada",
                "email": "ravi@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
        .
        .
  ]
}
The difference between [ and { - (Square brackets and Curly brackets)
If you observe normally JSON data will have square brackets and curly brackets. The difference between [ and { is, the square bracket represents starting of an JSONArray node whereas curly bracket represents JSONObject. While accessing these elements we need to call different methods to access these nodes.
json parsing structor
Writing JSON Parser Class
In your project create a class file and name it as JSONParser.java. The parser class has a method which will make http request to get JSON data and returns a JSONObject.
JSONParser.java
package com.androidhive.jsonparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

1. In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// 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;
2. Next step to is to use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
    // Getting Array of Contacts
    contacts = json.getJSONArray(TAG_CONTACTS);
    // looping through All Contacts
    for(int i = 0; i < contacts.length(); i++){
        JSONObject c = contacts.getJSONObject(i);
        // Storing each json item in variable
        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 number is agin 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);
    }
} catch (JSONException e) {
    e.printStackTrace();
}
Parsing JSON data and updating into ListView
In my previous tutorial Android ListView Tutorial i explained how to create listview and updating with list data. Below i am implementing same listview but the list data i am updating is from parsed JSON.
AndroidJSONParsingActivity.java
package com.androidhive.jsonparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidJSONParsingActivity extends ListActivity {
    // url to make request
    private static String url = "http://api.androidhive.info/contacts/";
    // 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;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CONTACTS);
            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);
                // Storing each json item in variable
                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 number is agin 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);
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_NAME, name);
                map.put(TAG_EMAIL, email);
                map.put(TAG_PHONE_MOBILE, mobile);
                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item,
                new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
                        R.id.name, R.id.email, R.id.mobile });
        setListAdapter(adapter);
        // selecting single ListView item
        ListView lv = getListView();
        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(TAG_NAME, name);
                in.putExtra(TAG_EMAIL, cost);
                in.putExtra(TAG_PHONE_MOBILE, description);
                startActivity(in);
            }
        });
    }
}
android json parsing list view


                                                                                                - PAVANKUMAR JOSHI