Monday, 12 August 2013

SAX parsing in android


ItemXMLHandler.java

import java.util.ArrayList;

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

public class ItemXMLHandler extends DefaultHandler {

 Boolean currentElement = false;
 String currentValue = "";
 Bean item = null;
 private ArrayList<Bean> itemsList = new ArrayList<Bean>();

 public ArrayList<Bean> getItemsList() {
  return itemsList;
 }

 // Called when tag starts
 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {

  currentElement = true;
  currentValue = "";

  if (localName.equals("item")) {
   item = new Bean();
  }

 }

 // Called when tag closing
 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {

  currentElement = false;

  if (localName.equals("id")) {
   item.setId(currentValue);
  } else if (localName.equals("title")) {
   item.setTitle(currentValue);
  } else if (localName.equals("desc")) {
   item.setDesc(currentValue);
  } else if (localName.equals("pubDate")) {
   item.setPubDate(currentValue);
  } else if (localName.equals("link")) {
   item.setLink(currentValue);
  } else if (localName.equals("item")) {
   itemsList.add(item);
  }
 }

 // Called to get tag characters
 @Override
 public void characters(char[] ch, int start, int length)
   throws SAXException {

  if (currentElement) {
   currentValue = currentValue + new String(ch, start, length);
  }
 }

}

Bean.java



public class Bean {

 private String id;
 private String title;
 private String desc;
 private String pubDate;
 private String link;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getDesc() {
  return desc;
 }

 public void setDesc(String desc) {
  this.desc = desc;
 }

 public String getPubDate() {
  return pubDate;
 }

 public void setPubDate(String pubDate) {
  this.pubDate = pubDate;
 }

 public String getLink() {
  return link;
 }

 public void setLink(String link) {
  this.link = link;
 }

}
MainActivity.java

import java.io.IOException;
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.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
 private ProgressDialog pDialog;
 private ItemXMLHandler myXMLHandler;
 private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
    private TextView textview;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  textview =(TextView)findViewById(R.id.textView1);
 }

 public void doParsing(View v){
  
  if (isNetworkAvailable()) {
   textview.setText("Loading...Please wait...");
   new AsyncData().execute(rssFeed);
  } else {
   showToast("No Network Connection!!!");
  } 
 }
 class AsyncData extends AsyncTask<String, Void, Void> {

  @Override
  protected void onPreExecute() {
   pDialog = new ProgressDialog(MainActivity.this);
   pDialog.setTitle("Loading....");
   pDialog.setMessage("Please wait...");
   pDialog.show();
   super.onPreExecute();
  }

  @Override
  protected Void doInBackground(String... params) {

   try {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    myXMLHandler = new ItemXMLHandler();
    xr.setContentHandler(myXMLHandler);

    URL _url = new URL(params[0]);

    xr.parse(new InputSource(_url.openStream()));

   } catch (ParserConfigurationException pce) {
    Log.e("SAX XML", "sax parse error", pce);
   } catch (SAXException se) {
    Log.e("SAX XML", "sax error", se);
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;

  }

  @Override
  protected void onPostExecute(Void result) {
   super.onPostExecute(result);

   textview.setText("Done!!!");
   if (pDialog != null && pDialog.isShowing()) {
    pDialog.dismiss();
   }

   ArrayList<Bean> itemsList = myXMLHandler.getItemsList();

   if (null != itemsList && itemsList.size() != 0) {
    for (int index = 0; index < itemsList.size(); index++) {
     Bean objBean = itemsList.get(index);

     System.out.println(">>>>>>>>>>>>>>>" + index);
     System.out.println("ID :: " + objBean.getId());
     System.out.println("TITLE :: " + objBean.getTitle());
     System.out.println("DESC :: " + objBean.getDesc());
     System.out.println("PUBDATE :: " + objBean.getPubDate());
     System.out.println("LINK :: " + objBean.getLink());
    }
   }
  }
 }

 public void showToast(String msg) {
  Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
 }

 public boolean isNetworkAvailable() {
  ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  if (connectivity == null) {
   return false;
  } else {
   NetworkInfo[] info = connectivity.getAllNetworkInfo();
   if (info != null) {
    for (int i = 0; i < info.length; i++) {
     if (info[i].getState() == NetworkInfo.State.CONNECTED) {
      return true;
     }
    }
   }
  }
  return false;
 }
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.samir"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.samir.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
res/layout 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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doParsing"
        android:text="Start" />

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

No comments:

Post a Comment