Tuesday, September 18, 2012

Sax Parser android Example

XML parsing in android

Here is the simplest way to parse XML and displaying into list view accordingly.You just have to care about how many tag you want  from your XML. Accordingly create a XML and base adapter.Now work is finish.

If you want to use this common XML file in  more than one ListView with different design then only create switch case.

AndroidChennaiActivity.java

public class AndroidChennaiActivity extends Activity 
{
private CommonClassFunction ccF;
ParsingXml sm=new ParsingXml();
 private ArrayList<String> tagName=new ArrayList<String>();
private ListView list;private ProgressDialog pd;
 @Override
 public void onCreate(Bundle savedInstanceState
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  list=(ListView) findViewById(R.id.list);

  tagName.add("vSmallImageDetail");

  tagName.add("vDescriptionDetail");
  tagName.add("vDurationDetail");
  tagName.add("dAddedDateDetail");
  pd=ProgressDialog.show(this,"Please wait","Loading...");
  pd.setCancelable(false);
  
  String url="www.demo.com";
  ccF=sm.new CommonClassFunction(this,tagName,list,pd,url);
  ccF.start();
 }
}

Common class that will perform everything in background thread and will display data in ListView

ParsingXml.java

public class ParsingXml extends DefaultHandler
{
 private int length;
 private boolean Error=false,flag=false;
 private ListView listview;
 private ProgressDialog pd;


 private ArrayList<String> [] store; 

 private ArrayList<String> tagName=new ArrayList<String>();
 private Activity act;
public ParsingXml(ArrayList<String> tag,int len)
 {
length=len;store=new ArrayList[length];
tagName=tag;
for(int i=0;i<length;i++)
  {
store[i]=new ArrayList<String>();
}
}

@Override

public void characters(char[] ch, int start, int lengthh)throws SAXException 
 {
super.characters(ch, start, lengthh);
String str=new String(ch,start,lengthh);
str=str.trim();
if(flag)
  {
for(int i=0;i<length;i++)
   {
if(tagName.get(i).equalsIgnoreCase(local))
    {
store[i].add(str);
}
}
}
}
 String local="";
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException 
 {
super.endElement(uri, localName, qName);
for(int i=0;i<length;i++)
  {
if(tagName.get(i).equalsIgnoreCase(localName))
   {
flag=false;
}
}
}

@Override

public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException 
 {
  super.startElement(uri, localName, qName, attributes);
for(int i=0;i<length;i++)
  {
if(tagName.get(i).equalsIgnoreCase(localName))
   {
flag=true;local=localName;
}
}
}

 private String str;

public class CommonClassFunction extends Thread
 {
  public CommonClassFunction(Activity actt,ArrayList<String> tag,ListView list,
  ProgressDialog pdD,String url)
  {
act=actt;tagName=tag;listview=list;pd=pdD;str=url;
}
@Override
public void run() 
  {
try
   {
  length=tagName.size();
act.runOnUiThread(all);
}
catch(Exception e)
   {
e.getMessage();
}
}
}

private Runnable all=new Runnable() 

 {
public void run() 
  {
try
   {
SAXParserFactory sFactory=SAXParserFactory.newInstance();
SAXParser sParser=sFactory.newSAXParser();
XMLReader xmlReader=sParser.getXMLReader();
px=new ParsingXml(tagName,length);
xmlReader.setContentHandler(px);
URL url=new URL(str);
url.openConnection();
xmlReader.parse(new InputSource(url.openStream()));
}
  catch(Exception e)
  {
e.getMessage();Error=true;
}
handler.sendEmptyMessage(0);
}
};

ParsingXml px;

private Handler handler=new Handler()
{
@Override
public void handleMessage(Message msg) 
  {
super.handleMessage(msg);
try
   {
if(length==0)
    {
Error=true;
}
    else if(Error)
    {
length=0;
}
if(Error)
    {
length=0;
}
switch(length)
    {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
      DealsAdapter da=new DealsAdapter(act, px.store[0],px.store[1],px.store[2],px.store[3]);
   listview.setAdapter(da);
break;
case 5:
break;
case 0: 
     ShowDialogBox("Error has occurred unknown reason");
}
pd.dismiss();
}
  catch(Exception e)
  {
e.getMessage();
}
 }
};

private void ShowDialogBox(String msg)

{
Builder builder=new AlertDialog.Builder(act);
builder.setTitle("Alerting");
builder.setMessage(msg);
builder.setPositiveButton("Ok",new DialogInterface.OnClickListener() 
  {
public void onClick(DialogInterface dialog, int which) 
   {
dialog.dismiss();
}
});
builder.show();
}
}

Simple Expandable ListView Android.


We are aware about android most powerful feature ListView. We can handle ListView click event eg. clicking on ListView row, we can start a new activity or what ever we want to do.

But it some how strange to many developer, clicking on ListView row it should expand and show more details in spite of opening a new Activity and we can shrink row of ListView after reading details information. This is feature known as ExpandableListView in android.

ExpandableListView is pre-define widget in android . and much similar to android ListView.So here we go for ExpandableListView Simple Example with source code at the end of this article.
Step 1)  create one project. There is only one class to explain here


 package com.ahmad.expandable;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 import java.util.List;  
 import java.util.Map;  
 import android.app.ExpandableListActivity;  
 import android.os.Bundle;  
 import android.widget.ExpandableListAdapter;  
 import android.widget.SimpleExpandableListAdapter;  
 /**  
  * Demonstrates expandable lists backed by a Simple Map-based adapter  
  */  
 public class ExpandableList extends ExpandableListActivity {  
   private static final String NAME = "NAME";  
   private static final String IS_EVEN = "IS_EVEN";  
   private ExpandableListAdapter mAdapter;  
   @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();  
     List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();  
     for (int i = 0; i < 20; i++) {  
       Map<String, String> curGroupMap = new HashMap<String, String>();  
       groupData.add(curGroupMap);  
       curGroupMap.put(NAME, "Group " + i);  
       curGroupMap.put(IS_EVEN, (i % 2 == 0) ? "This group is even" : "This group is odd");  
       List<Map<String, String>> children = new ArrayList<Map<String, String>>();  
       for (int j = 0; j < 15; j++) {  
         Map<String, String> curChildMap = new HashMap<String, String>();  
         children.add(curChildMap);  
         curChildMap.put(NAME, "Child " + j);  
         curChildMap.put(IS_EVEN, (j % 2 == 0) ? "This child is even" : "This child is odd");  
       }  
       childData.add(children);  
     }  
     // Set up our adapter  
     mAdapter = new SimpleExpandableListAdapter(  
         this,  
         groupData,  
         android.R.layout.simple_expandable_list_item_1,  
         new String[] { NAME, IS_EVEN },  
         new int[] { android.R.id.text1, android.R.id.text2 },  
         childData,  
         android.R.layout.simple_expandable_list_item_2,  
         new String[] { NAME, IS_EVEN },  
         new int[] { android.R.id.text1, android.R.id.text2 }  
         );  
     setListAdapter(mAdapter);  
   }  
 }  



                                                    Screen Shot of example




                                                            

Step 2)  This is step is simple. Download project. And import it to your work space and play with the code as per requirement 

                     

                                 DOWNLOAD SOURCE CODE 

ListView with image android


ListView is core component of android. Its feature of binding data dynamically and efficient loading is awesome. It give us lots of command and make our task easy.

There are three component in Listview Android

  • ListView Control Widget
  • Base Adapter
  • Activity
Base Adapter is used to bind data dynamically inside Listrow. So these are the few basic steps to create a Listview in Android

Step 1). Create Two Layout, one for Listview and activity background Second for ListView Row


Step 2) Create one Activity as controller to control and work like a bridge between BaseAdapter and Layout


Step 3) Adapter( or so called BaseAdapter)

You can download source code and play with it. This code output will be like that

Complex ListView
ListView With Image
Biggest advantage of using BaseAdapter and ListView, is its efficient loading capacity. BaseAdapter bind view to ListView when every row created first time then it keeps all already created row in memory and load them from memory. This make ListView damn fast

In my code i have Holder class that make sure that we will inflate a row layout only when row is created first time
                                                                      

                                                          Download Source Code