Mehmet Ethem SULAN :: Android :: Android SAX Parser XML Parsing from the Net Custom ListView ListActivity

Android ile SAX Parser kullanarak cd_catalog.xml urlsindeki xmli parse ettim ve SimpleAdapter kullanarak Custom Listview de listeledim. Daha iyi anlamanız için Android XML Parsing from Internet with DOM Multichoice ArrayAdapter Sample örneğine bakın.
Output

customListView

DefaultHandler metodlarını override ettim

DefaultHandler


ParsingXML.java

package com.xml.parser;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class ParsingXML extends ListActivity {
    private ArrayList<HashMap<String, String>> xmlList=new ArrayList<HashMap<String, String>>();
    private ItemsCD itemsCD;
    private CustomXmlHandler customXmlHandler;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//Note: ListActivity kullandigimizdan setContentView(R.layout.main); atamasini yapmiyoruz.
//Ayrica main.xml içindeki ListView componentine findById() metodu ile erişmiyoruz.Çünkü ListActivity kullanıyoruz
        itemsCD=new ItemsCD();
        xmlList=getListFromXml();

    }
	private ArrayList<HashMap<String, String>> getListFromXml()  {
//localde arraylist içinde hashmap  oluşturuyoruz ve elemanları hashmapleri ekliyoruz
		ArrayList<HashMap<String, String>> list=new ArrayList<HashMap<String, String>>();
			try {
//XML için url dir. Çalıştırıken URL bu urlde .xml dosyasının olup olmadığını kontrol edin
				URL url=new URL("http://www.xmlfiles.com/examples/cd_catalog.xml");
//SAX ile XMl parse ettim
				SAXParserFactory sFactory=SAXParserFactory.newInstance();
				SAXParser sParser = sFactory.newSAXParser();

				XMLReader xmlReader=sParser.getXMLReader();

				customXmlHandler=new CustomXmlHandler();
				xmlReader.setContentHandler(customXmlHandler);
				xmlReader.parse(new InputSource(url.openStream()));

			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

//CustomXmlHandler sinifinda ItemsCD startElement() metodunda bir nesne oluşturuluyor ve bu nesne üzerinden
//ItemsCD.ajav içindeki ArrayListlere xmldeki datalar set ediliyor ve o obje getItemsCD() ile dönderiyoruz.
			itemsCD=customXmlHandler.getItemsCD();
//itemsCD.getArtist().size() kadar for da dönüyor ve diğer ArrayListedeki değerler HashMape ekleniyor ve o da ArrayListeye ekelniyor.
			for (int i = 0; i < itemsCD.getArtist().size(); i++) {
				HashMap<String, String> hashMap=new HashMap<String, String>();
				hashMap.put("ARTIST", itemsCD.getArtist().get(i));
				hashMap.put("TITLE", itemsCD.getTitle().get(i));
				hashMap.put("COUNTRY",itemsCD.getCountry().get(i));
				hashMap.put("COMPANY",itemsCD.getCompany().get(i));
				hashMap.put("PRICE",itemsCD.getPrice().get(i));
				hashMap.put("YEAR",itemsCD.getYear().get(i));
//ArrayListe ye ekle
				list.add(hashMap);
			}

		return list;
	}
	@Override
	protected void onStart() {
		super.onStart();
//SimleAdapter olusturuyoruz ve main.xml içindeki ListView e atiyoruz.
//from dedigi HashMap teki key lerdir
		String[] from={"ARTIST","TITLE","COUNTRY","COMPANY","PRICE","YEAR"};
//to dediği country.xml deki textview lerdir. Mesela Artist için: R.id.textView1
		int[] to=new int[]{R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4,R.id.textView5,R.id.textView6};
		SimpleAdapter listAdapter=new SimpleAdapter(getApplicationContext(), xmlList, R.layout.country, from, to);
        this.setListAdapter(listAdapter);

	}
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
//List itemlar click edildiğinde o andaki bütün değerleri toast mesajı olarak gösteriyorum.
	    Toast.makeText(this, xmlList.get(position).toString(), Toast.LENGTH_LONG).show();
	}
}

CustomXmlHandler.java

package com.xml.parser;

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

//Bu DefaultHandler çok iyi yazılmış. Tam nasıl çalıştığınızı anlamak için debug edin mutlaka.
public class CustomXmlHandler extends DefaultHandler {

	Boolean currentElement=false;
	String curValue=null;
	private ItemsCD itemsCD;

	public ItemsCD getItemsCD() {
		return itemsCD;
	}

	public void setItemsCD(ItemsCD itemsCD) {
		this.itemsCD = itemsCD;
	}

	@Override
	public void characters(char[] ch, int start, int length)throws SAXException {
		super.characters(ch, start, length);
		if(currentElement){
			curValue=new String(ch, start, length);
			currentElement=false;
		}

	}

	@Override
	public void endElement(String uri, String localName, String qName)throws SAXException {
		super.endElement(uri, localName, qName);
		currentElement=false;
		if(localName.equalsIgnoreCase("TITLE")){
			itemsCD.setTitle(curValue);
		}else if(localName.equalsIgnoreCase("ARTIST")){
			itemsCD.setArtist(curValue);
		}else if(localName.equalsIgnoreCase("COUNTRY")){
			itemsCD.setCountry(curValue);
		}else if(localName.equalsIgnoreCase("COMPANY")){
			itemsCD.setCompany(curValue);
		}else if(localName.equalsIgnoreCase("PRICE")){
			itemsCD.setPrice(curValue);
		}else if(localName.equalsIgnoreCase("YEAR")){
			itemsCD.setYear(curValue);
		}

	}

	@Override
	public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		currentElement=true;
//XML deki root elementtir.
		if(localName.equals("CATALOG")){
			itemsCD=new ItemsCD();
		}

	}

}

country.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:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="TextView" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="TextView" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="TextView" android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="TextView" android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="TextView" android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>

AndroidManifest.xml

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

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="ParsingXML"
                  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>

Download Android/XmlParserSAX.tar.gz

Comments

There are 2 comments for this post.

  1. tolgahan on Ekim 20, 2011 8:50 am

    Abicim yazılarında eksik yerler var ItemsCD classını nasıl oluşturuyoruz neden oluşturuyoruz belirtmemişşin.

  2. tolgahan on Ekim 20, 2011 8:51 am

    Abicim yazılarında eksik yerler var ItemsCD classını nasıl oluşturuyoruz neden oluşturuyoruz belirtmemişşiniz.

Write a Comment

Let me know what you think?