Monday 6 January 2014

SAXParser example in Android



activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_parse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="parse" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MainActivity.java:
package com.ram.saxparserexample;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    URL url;
    ArrayList<String> list = new ArrayList<String>();
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button parse = (Button) findViewById(R.id.button_parse);
        text = (TextView) findViewById(R.id.textView1);

        parse.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                MyAsync ma = new MyAsync();
                ma.execute();

            }
        });

    }

    class MyAsync extends AsyncTask<Void, Void, Void> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pd = ProgressDialog.show(MainActivity.this, "", "loading");
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            try {
                url = new URL("http://www.w3schools.com/xml/note.xml");

                // Create an instance for SAXParserFactory
                SAXParserFactory mySAXParserFactory = SAXParserFactory
                        .newInstance();

                // Create an instance for SAXParser
                SAXParser mySAXParser = mySAXParserFactory.newSAXParser();

                // Create an instance for XMLReader
                XMLReader myXMLReader = mySAXParser.getXMLReader();

                // Create an instance for customized handler class
                XMLHandler myXMLHandler = new XMLHandler();

                // apply handler to the XMLReader
                myXMLReader.setContentHandler(myXMLHandler);

                // open the connection
                InputSource is = new InputSource(url.openStream());

                is.setEncoding("ISO-8859-1");

                // parse the data
                myXMLReader.parse(is);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pd.cancel();

            for (String s : list) {
                text.append(s + "\n");
            }
        }

    }

    class XMLHandler extends DefaultHandler {
        boolean to = false;
        boolean from = false;
        boolean heading = false;
        boolean body = false;

        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            // TODO Auto-generated method stub
            super.startElement(uri, localName, qName, attributes);

            if (localName.equals("to")) {
                this.to = true;
            } else if (localName.equals("from")) {
                this.from = true;
            } else if (localName.equals("heading")) {
                this.heading = true;
            } else if (localName.equals("body")) {
                this.body = true;
            }
        }

        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            // TODO Auto-generated method stub
            super.characters(ch, start, length);
            if (this.to) {
                list.add(new String(ch, start, length));
            } else if (this.from) {
                list.add(new String(ch, start, length));

            } else if (this.heading) {
                list.add(new String(ch, start, length));

            } else if (this.body) {
                list.add(new String(ch, start, length));

            }

        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            // TODO Auto-generated method stub
            super.endElement(uri, localName, qName);
            if (localName.equals("to")) {
                this.to = false;
            } else if (localName.equals("from")) {
                this.from = false;
            } else if (localName.equals("heading")) {
                this.heading = false;
            } else if (localName.equals("body")) {
                this.body = false;
            }
        }
    }
}

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.saxparserexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.saxparserexample.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

No comments:

Post a Comment