Sunday 19 January 2014

SAX Parser Example with Custom ListView







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" >

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

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#990066"
        android:dividerHeight="3dp" >
    </ListView>

</LinearLayout>

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

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

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#0000ff" />

</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.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
    URL url;
    ListView list;

    ArrayList<String> titles = new ArrayList<String>();
    ArrayList<String> artists = new ArrayList<String>();
    ArrayList<String> countries = new ArrayList<String>();
    ArrayList<String> companies = new ArrayList<String>();
    ArrayList<String> prices = new ArrayList<String>();
    ArrayList<String> years = new ArrayList<String>();

    TextView text;

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

        list = (ListView) findViewById(R.id.listView1);

        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.xmlfiles.com/examples/cd_catalog.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();
            CustomAdapter ca = new CustomAdapter();
            list.setAdapter(ca);
        }

    }

    class XMLHandler extends DefaultHandler {

        boolean TITLE = false;
        boolean ARTIST = false;
        boolean COUNTRY = false;
        boolean COMPANY = false;
        boolean PRICE = false;
        boolean YEAR = 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("TITLE")) {
                this.TITLE = true;
            } else if (localName.equals("ARTIST")) {
                this.ARTIST = true;
            } else if (localName.equals("COUNTRY")) {
                this.COUNTRY = true;
            } else if (localName.equals("COMPANY")) {
                this.COMPANY = true;
            } else if (localName.equals("PRICE")) {
                this.PRICE = true;
            } else if (localName.equals("YEAR")) {
                this.YEAR = 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.TITLE) {
                titles.add(new String(ch, start, length));
            } else if (this.ARTIST) {
                artists.add(new String(ch, start, length));

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

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

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

            } else if (this.YEAR) {
                years.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("TITLE")) {
                this.TITLE = false;
            } else if (localName.equals("ARTIST")) {
                this.ARTIST = false;
            } else if (localName.equals("COUNTRY")) {
                this.COUNTRY = false;
            } else if (localName.equals("COMPANY")) {
                this.COMPANY = false;
            } else if (localName.equals("PRICE")) {
                this.PRICE = false;
            } else if (localName.equals("YEAR")) {
                this.YEAR = false;
            }
        }
    }

    class CustomAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return titles.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int index, View v, ViewGroup arg2) {
            // TODO Auto-generated method stub
            v = getLayoutInflater().inflate(R.layout.custom, null);

            TextView t1 = (TextView) v.findViewById(R.id.textView1);
            TextView t2 = (TextView) v.findViewById(R.id.textView2);
            TextView t3 = (TextView) v.findViewById(R.id.textView3);
            TextView t4 = (TextView) v.findViewById(R.id.textView4);
            TextView t5 = (TextView) v.findViewById(R.id.textView5);
            TextView t6 = (TextView) v.findViewById(R.id.textView6);

            t1.setText(titles.get(index).toString());
            t2.setText(artists.get(index).toString());
            t3.setText(countries.get(index).toString());
            t4.setText(companies.get(index).toString());
            t5.setText(prices.get(index).toString());
            t6.setText(years.get(index).toString());

            return v;
        }

    }
}


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