Showing posts with label SAX Parser. Show all posts
Showing posts with label SAX Parser. Show all posts

Android JSON Parser Example



In this example we will see how to parse a JavaScript Object Notation(JSON) response. Here we will use a set of classes from the org.json package offered in Android SDK by simply creating new JSONObject from the formatted string data.

Let us parse the following JSON response:

JSON response:
{
“person”:{
“name”:“Jack”,
“age”:27
}
}
1.Create a new project File ->New -> Project ->Android ->Android Application Project. Follow the wizard to create a project. After the project is created in the layout file activity_main.xml (in my case) create two text views and give the id as name and age. Refer the below code.

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="110dp"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

    <TextView
        android:id="@+id/age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>

2.Now in the corresponding java file MainActivity.java (in my case) we will put the JSON response in a string and parse it. Since JSON parser is strict by default , meaning the execution will halt with an exception if an invalid JSON data is found or no data is found.

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 = "{\"person\":{\"name\":\"Jack Sparrow\",\"age\":27}}";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  TextView name = (TextView) findViewById(R.id.name);
  TextView age = (TextView) findViewById(R.id.age);
  try {
   JSONObject person = (new JSONObject(JSON_STRING))
     .getJSONObject("person");
   String Name = person.getString("name");
   int Age = person.getInt("age");
   name.setText("Whats the name?\n" + Name);
   age.setText("Whats the age?\n" + Age);
  } catch (JSONException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}
3.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:



Android SAX Parser Example


In this example we will see how to parse an XML file using SAX Parser in Android. What we do here is load the .xml file in the assets folder and parse the content inside and show them in a text view.

To do parsing we use the following callback methods :
  • startDocument() and endDocument() is called at the start and end of the document.
  • startElement() and endElement() is called at the start and end of the element.
  • characters() is called with the text contents between the element.
So let us start:

1.Create an xml file (file.xml) like below

file.xml

<?xml version="1.0"?>
<contacts>
<contact>
<firstname>Sachin</firstname>
<lastname>Tendulkar</lastname>
<email>sachin@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Brain</firstname>
<lastname>Lara</lastname>
<email>lara@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Steve</firstname>
<lastname>Waugh</lastname>
<email>steve@xyz.com</email>
<phone>9999999999</phone>
</contact>
</contacts>
2. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project give activity name as SAXParserActivity(SAXParserActivity.java). Copy and paste the xml file inside the assets folder of the android project. In the activity we parse the xml file using the org.xml.sax.helpers.DefaultHandler.

SAXParserActivity.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 SAXParserActivity extends Activity {
 TextView tv;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv = (TextView) findViewById(R.id.textView1);
  try {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser saxParser = factory.newSAXParser();
   DefaultHandler handler = new DefaultHandler() {
    boolean bfname = false;
    boolean blname = false;
    boolean bemail = false;
    boolean bphone = false;

    public void startElement(String uri, String localName,
      String qName, Attributes attributes)
      throws SAXException {
     if (qName.equalsIgnoreCase("FIRSTNAME")) {
      bfname = true;
     }
     if (qName.equalsIgnoreCase("LASTNAME")) {
      blname = true;
     }
     if (qName.equalsIgnoreCase("EMAIL")) {
      bemail = true;
     }
     if (qName.equalsIgnoreCase("PHONE")) {
      bphone = true;
     }
    }

    public void endElement(String uri, String localName,
      String qName) throws SAXException {
    }

    public void characters(char ch[], int start, int length)
      throws SAXException {
     if (bfname) {
      tv.setText(tv.getText() + "\n\n First Name : "
        + new String(ch, start, length));
      bfname = false;
     }
     if (blname) {
      tv.setText(tv.getText() + "\n Last Name : "
        + new String(ch, start, length));
      blname = false;
     }
     if (bemail) {
      tv.setText(tv.getText() + "\n Email : "
        + new String(ch, start, length));
      bemail = false;
     }
     if (bphone) {
      tv.setText(tv.getText() + "\n Phone : "
        + new String(ch, start, length));
      bphone = false;
     }
    }
   };
   InputStream is = this.getAssets().open("file.xml");
   saxParser.parse(is, handler);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
3. Now in the main.xml, add the id attribute for the TextView to be used in the SAXParserActivity


main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="SAX Parser Example" />

</LinearLayout>
4.Run the project by rightclicking project Run as → android project. This project is tested with amdroid API level 8

Output:

The output of this example would be similar to the one as follows: