My Life with Android
Introduction Android Componets UserInterface Advanced UI Data Storage Advanced Concepts Others New Studio

Android XML Parsing using SAX Parser

  • Android provides the facility to parse the xml file using SAX, DOM etc. parsers.
  • The SAX parser cannot be used to create the XML file, It can be used to parse the xml file only.

Example of android SAX Xml parsing

File: file.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  
  
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="75dp"  
        android:layout_marginTop="46dp"  
        android:text="TextView" />  
  
</RelativeLayout> 

xml document

Create an xml file named file.xml inside the assets directory of your project.
File: activity_main.xml

<?xml version="1.0"?>  
<records>  
<employee>  
<name>Sachin Kumar</name>  
<salary>50000</salary>  
</employee>  
<employee>  
<name>Rahul Kumar</name>  
<salary>60000</salary>  
</employee>  
<employee>  
<name>John Mike</name>  
<salary>70000</salary>  
</employee>  
</records> 


Now write the code to parse the xml using sax parser.
File: MainActivity.java

import java.io.InputStream;  
import javax.xml.parsers.SAXParser;  
import javax.xml.parsers.SAXParserFactory;  
import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;  
import android.app.Activity;  
import android.os.Bundle;  
import android.widget.TextView;  
public class MainActivity extends Activity {  
TextView tv;  
@Override  
  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.activity_main);  
tv=(TextView)findViewById(R.id.textView1);  
try {  
SAXParserFactory factory = SAXParserFactory.newInstance();  
  
SAXParser saxParser = factory.newSAXParser();  
  
  
DefaultHandler handler = new DefaultHandler() {  
  
boolean name = false;  
  
boolean salary = false;  
  
  
public void startElement(String uri, String localName,String qName,  
Attributes attributes) throws SAXException {  
if (qName.equalsIgnoreCase("name"))  
{  
name = true;  
}  
if (qName.equalsIgnoreCase("salary"))  
{  
salary = true;  
}  
}//end of startElement method  
public void endElement(String uri, String localName,  
String qName) throws SAXException {  
}  
  
public void characters(char ch[], int start, int length) throws SAXException {  
if (name) {  
  
tv.setText(tv.getText()+"\n\n Name : " + new String(ch, start, length));  
name = false;  
}  
if (salary) {  
tv.setText(tv.getText()+"\n Salary : " + new String(ch, start, length));  
salary = false;  
}  
}//end of characters  
 method  
};//end of DefaultHandler object  
  
InputStream is = getAssets().open("file.xml");  
saxParser.parse(is, handler);  
  
} catch (Exception e) {e.printStackTrace();}  
}  
}  

OUTPUT :

Android XML Parsing using DOM Parser

  • We can parse the xml document by dom parser also.
  • It can be used to create and parse the xml file.

Example of android DOM Xml parsing

File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  
  
    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="75dp"  
        android:layout_marginTop="46dp"  
        android:text="TextView" />  
  
</RelativeLayout> 


xml document

Create an xml file named file.xml inside the assets directory of your project.
File: file.xml

<?xml version="1.0"?>  
<records>  
<employee>  
<name>Sachin Kumar</name>  
<salary>50000</salary>  
</employee>  
<employee>  
<name>Rahul Kumar</name>  
<salary>60000</salary>  
</employee>  
<employee>  
<name>John Mike</name>  
<salary>70000</salary>  
</employee>  
</records>

Let's write the code to parse the xml using dom parser.
File: MainActivity.java

import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
import android.app.Activity;  
import android.os.Bundle;  
import android.widget.TextView;  
  
public class MainActivity extends Activity {  
TextView tv1;  
  
@Override  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.activity_main);  
tv1=(TextView)findViewById(R.id.textView1);  
try {  
InputStream is = getAssets().open("file.xml");  
  
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
Document doc = dBuilder.parse(is);  
  
Element element=doc.getDocumentElement();  
element.normalize();  
  
NodeList nList = doc.getElementsByTagName("employee");  
for (int i=0; i<nList.getLength(); i++) {  
  
Node node = nList.item(i);  
if (node.getNodeType() == Node.ELEMENT_NODE) {  
Element element2 = (Element) node;  
tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");  
tv1.setText(tv1.getText()+"Salary : " + getValue("salary", element2)+"\n");  
tv1.setText(tv1.getText()+"-----------------------");  
}  
}//end of for loop  
  
} catch (Exception e) {e.printStackTrace();}  
  
}  
private static String getValue(String tag, Element element) {  
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();  
Node node = (Node) nodeList.item(0);  
return node.getNodeValue();  
}  
  
}  


OUTPUT :

Android XMLPullParser Tutorial

  • Android recommends to use XMLPullParser to parse the xml file than SAX and DOM because it is fast.
  • The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML document using XMLPullParser.

Events of XmlPullParser

The next() method of XMLPullParser moves the cursor pointer to the next event. Generally, we use four constants (works as the event) defined in the XMLPullParser interface.
  • START_TAG : An XML start tag was read.
  • TEXT : Text content was read; the text content can be retrieved using the getText() method.
  • END_TAG : An end tag was read.
  • END_DOCUMENT : No more events are available.

Example of android XMLPullParser

File: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  
  
    <ListView  
        android:id="@+id/listView1"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content" >  
  
    </ListView>  
  
</RelativeLayout> 


Create an xml file named employees.xml inside the assets directory of your project.
File: employees.xml

<?xml version="1.0" encoding="UTF-8"?>  
<employees>  
    <employee>  
        <id>1</id>  
        <name>Sachin</name>  
        <salary>50000</salary>        
    </employee>  
    <employee>  
        <id>2</id>  
        <name>Nikhil</name>  
        <salary>60000</salary>    
    </employee>  
      
</employees>

Employee class

Now create the Employee class that corresponds to the xml file.
File: Employee.java

public class Employee {  
     private int id;  
     private String name;  
     private float salary;  
        public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public float getSalary() {  
        return salary;  
    }  
    public void setSalary(float salary) {  
        this.salary = salary;  
    }  
  
    @Override  
    public String toString() {  
        return " Id= "+id + "\n Name= " + name + "\n Salary= " + salary;  
    }  
}  

XMLPullParserHandler class

Now write the code to parse the xml file using XMLPullParser. Here, we are returning all the employee in list.
File: XMLPullParserHandler.java

import java.io.IOException;  
import java.io.InputStream;  
import java.util.ArrayList;  
import java.util.List;  
import org.xmlpull.v1.XmlPullParser;  
import org.xmlpull.v1.XmlPullParserException;  
import org.xmlpull.v1.XmlPullParserFactory;  
   
  
public class XmlPullParserHandler {  
    private List<Employee> employees= new ArrayList<Employee>();  
    private Employee employee;  
    private String text;  
   
    public List<Employee> getEmployees() {  
        return employees;  
    }  
   
    public List<Employee> parse(InputStream is) {  
           try {  
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
            factory.setNamespaceAware(true);  
            XmlPullParser  parser = factory.newPullParser();  
   
            parser.setInput(is, null);  
   
            int eventType = parser.getEventType();  
            while (eventType != XmlPullParser.END_DOCUMENT) {  
                String tagname = parser.getName();  
                switch (eventType) {  
                case XmlPullParser.START_TAG:  
                    if (tagname.equalsIgnoreCase("employee")) {  
                        // create a new instance of employee  
                        employee = new Employee();  
                    }  
                    break;  
   
                case XmlPullParser.TEXT:  
                    text = parser.getText();  
                    break;  
   
                case XmlPullParser.END_TAG:  
                    if (tagname.equalsIgnoreCase("employee")) {  
                        // add employee object to list  
                        employees.add(employee);  
                    }else if (tagname.equalsIgnoreCase("id")) {  
                        employee.setId(Integer.parseInt(text));  
                    }  else if (tagname.equalsIgnoreCase("name")) {  
                        employee.setName(text);  
                    } else if (tagname.equalsIgnoreCase("salary")) {  
                        employee.setSalary(Float.parseFloat(text));  
                    }   
                    break;  
   
                default:  
                    break;  
                }  
                eventType = parser.next();  
            }  
   
        } catch (XmlPullParserException e) {e.printStackTrace();}   
        catch (IOException e) {e.printStackTrace();}  
   
        return employees;  
    }  
}  

MainActivity class

Now, write the code to display the list data in the ListView.
File: MainActivity.java

import java.io.IOException;  
import java.io.InputStream;  
import java.util.List;  
  
import android.os.Bundle;  
import android.app.Activity;  
import android.view.Menu;  
import android.widget.ArrayAdapter;  
import android.widget.ListView;  
  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
       ListView listView = (ListView) findViewById(R.id.listView1);  
          
        List<Employee> employees = null;  
        try {  
            XmlPullParserHandler parser = new XmlPullParserHandler();  
            InputStream is=getAssets().open("employees.xml");  
            employees = parser.parse(is);  
              
            ArrayAdapter<Employee> adapter =new ArrayAdapter<Employee>  
    (this,android.R.layout.simple_list_item_1, employees);  
            listView.setAdapter(adapter);  
              
        } catch (IOException e) {e.printStackTrace();}  
          
    }  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.activity_main, menu);  
        return true;  
    }  
      
}  

OUTPUT :

Android JSON Parser Tutorial

  • JSON (Javascript Object Notation) is a programming language .
  • It is an alternative to XML.
  • Android provides support to parse the JSON object and array.
    Advantage of JSON over XML
  • JSON is faster and easier than xml for AJAX applications.
  • Unlike XML, it is shorter and quicker to read and write.
  • It uses array.
  • 1. JSON Object

    • A JSON object contains key/value pairs like map.
    • The keys are strings and the values are the JSON types.
    • Keys and values are separated by comma.
    • The { (curly brace) represents the json object.
    
    {  
        "employee": {  
            "name":       "sachin",   
            "salary":      56000,   
            "married":    true  
        }  
    }
    
    

    2. JSON Array

    The [ (square bracket) represents the json array.
    
    { "Employee" :  
        [  
         {"id":"101","name":"Sonoo Jaiswal","salary":"50000"},  
         {"id":"102","name":"Vimal Jaiswal","salary":"60000"}  
        ]   
    }
    
    

    Example of android JSON parsing

    File: activity_main.xml
    
    <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
        xmlns:tools="http://schemas.android.com/tools"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        tools:context=".MainActivity" >  
      
        <TextView  
            android:id="@+id/textView1"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_alignParentLeft="true"  
            android:layout_alignParentTop="true"  
            android:layout_marginLeft="75dp"  
            android:layout_marginTop="46dp"  
            android:text="TextView" />  
      
    </RelativeLayout>
    
    
    
    File: MainActivity.java
    
    import org.json.JSONException;  
    import org.json.JSONObject;  
    import android.app.Activity;  
    import android.os.Bundle;  
    import android.widget.TextView;  
      
    public class MainActivity extends Activity {  
    public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";  
      
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
      
    TextView textView1=(TextView)findViewById(R.id.textView1);  
      
    try{  
    JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");  
    String empname=emp.getString("name");  
    int empsalary=emp.getInt("salary");  
      
    String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;  
    textView1.setText(str);  
      
    }catch (Exception e) {e.printStackTrace();}  
      
    }  
      
    }    
    
    
    OUTPUT :

    2. Parsing JSONArray in Android

    By the help of JSONArray class, you can parse the JSONArray containing the JSON Objects. File: MainActivity.java
    
    import org.json.JSONArray;  
    import org.json.JSONException;  
    import org.json.JSONObject;  
    import android.app.Activity;  
    import android.os.Bundle;  
    import android.widget.TextView;  
      
    public class MainActivity extends Activity {  
       @Override  
        protected void onCreate(Bundle savedInstanceState) {  
             super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
               
            TextView output = (TextView) findViewById(R.id.textView1);  
               
            String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\",\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";  
              
                   String data = "";  
                   try {  
                         // Create the root JSONObject from the JSON string.  
                       JSONObject  jsonRootObject = new JSONObject(strJson);  
      
                       //Get the instance of JSONArray that contains JSONObjects  
                        JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");  
                         
                        //Iterate the jsonArray and print the info of JSONObjects  
                        for(int i=0; i < jsonArray.length(); i++){  
                            JSONObject jsonObject = jsonArray.getJSONObject(i);  
                               
                            int id = Integer.parseInt(jsonObject.optString("id").toString());  
                            String name = jsonObject.optString("name").toString();  
                            float salary = Float.parseFloat(jsonObject.optString("salary").toString());  
                               
                            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";  
                          }  
                        output.setText(data);  
                     } catch (JSONException e) {e.printStackTrace();}  
          }  
    } 
    
    
    
    OUTPUT :

    POST JSON Array Data using Volley Lib

    POST JSON Array Data using Volley Lib

    
    package com.example.androidcollegeppt;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.Bundle;
    
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    
    public class SubmitJSONArray extends Activity{
    	ProgressDialog pd1;
    	String post_data;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.a_json_submitdata);
    		JSONArray jData = new JSONArray();
    		try{
    			for (int i = 0; i < 5; i++) {
    				JSONObject jObj = new JSONObject();
    				jObj.put("employee_id", "989898"+i);
    				jObj.put("question_id", "question-"+i);
    				jObj.put("answer", "answer-"+i);
    				jData.put(jObj);
    			}
    		}catch(Exception e){}
    		post_data=jData.toString();
    		pd1 = new ProgressDialog(SubmitJSONArray.this);
    		pd1.setMessage("Please wait, Data is being Loaded.");
    		pd1.show();
    		// Request a string response
    		StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://telugucenimaentertainment.com/GoogleMaps/testJson.php", new Response.Listener<String>() {
    			@Override
    			public void onResponse(String response) {
    				pd1.hide();
    				pd1.cancel();
    			}
    		}, new Response.ErrorListener() {
    			@Override
    			public void onErrorResponse(VolleyError error) {
    				pd1.hide();
    				pd1.cancel();
    			}
    		}){
    			@Override
    			protected Map<String, String> getParams() {
    				Map<String, String> params = new HashMap<String, String>();
    				params.put("json",post_data);
    				return params;
    			}
    		};
    
    		Volley.newRequestQueue(this).add(stringRequest);
    		
    	}
    
    }