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

Thursday, August 16, 2012

ViewFlipper and SlidingDrawer example Android


In my last post i talked about android selector mechanism and how to customize default GUI components apperances. another issue with mobile phone applications is limited displaying space, i mean if your application wants to go a bit further than a basic , simple application, it is almost gonna be impossible to fit all GUI options and features in a relatively small displaying space of mobile phones.

as we've already talked about it, the first option to solve this sort of problems is Menus and dialogs which are pretty easy to use and simple, but what if you need something more than that with higher level of customizability, that's whenViewFlipper and SlidingDrawer come into play(although they could be used for other purposes as well), like menus and dialogs they enable us to have some views hidden and show them when they are requested or when it's appropriate.



first of all let's see what a ViewFlipper is, ViewFlipper is Actually a View container which can hold different Views, but it shows just one of those Views at a time and hide others, you can switch between views manually or automatically, most interesting thing about ViewFlipper is that it uses two different Animations for flipping between views, one is used for outgoing View and the other one for incoming View.


There are two views between which we wanna flip, a ListView (Which we talked about it last time) and a simple view with a text and a button on it, When we press "Next" button our ListView will slide out and the other view will slide in and when "Go Back" button is pressed two views will be switched again. 

our XML will be something like this : 

<ViewFlipper 
       android:id="@+id/flipper"
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent">
  <FrameLayout 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content"
       android:layout_gravity="top" 
       android:layout_marginTop="50dip">
    <ListView 
        android:id="@+id/list" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:dividerHeight="0dip"
        android:divider="@null" 
        android:listSelector="@drawable/list_selector"
        android:layout_gravity="center" /> 
  </FrameLayout>
  <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:orientation="vertical"
        android:background="@drawable/wood01" 
        android:padding="20dip"
        android:layout_gravity="top" 
        android:layout_marginTop="50dip">
     <TextView 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"
          android:text="TEST" 
          android:layout_gravity="center" 
          android:padding="15dip"
          android:textSize="22dip" 
          android:textColor="@color/white" />
    <Button 
          android:text="Go Back" 
          android:id="@+id/back_btn"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" />
  </LinearLayout>
 </ViewFlipper>

As you can see our ViewFlipper has two children, a FrameLayout containing the ListView and a LinearLayout containing a TextView and a Button. by default the first child is shown when application comes up for the first time.

Setting Animation for our flipper is pretty easy and straigh forward, here's the code I've used :

  this.flipper = (ViewFlipper)findViewById(R.id.flipper);
        
  Animation s_in  = AnimationUtils.loadAnimation(this, R.anim.slidein);
  Animation s_out = AnimationUtils.loadAnimation(this, R.anim.slideout);
  this.flipper.setInAnimation(s_in);
  this.flipper.setOutAnimation(s_out);

and here are the content of slidein.xml and slideout.xml respectively : 

<?xml version="1.0" encoding="utf-8"?>
<set 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:interpolator="@android:anim/decelerate_interpolator">
    <translate 
        android:fromXDelta="-100%" 
        android:toXDelta="0%" 
        android:duration="1800" />    
</set>
<?xml version="1.0" encoding="utf-8"?>
<set 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:interpolator="@android:anim/decelerate_interpolator">     
    <translate 
        android:fromXDelta="0%" 
        android:toXDelta="100%" 
        android:duration="1800" />    
</set>

All you need to do to switch the showing view manually is to use showNext() and showPrevious() methods of ViewFlipper class.
Another predefined Widget for hiding stuff is SlidingDrawer and its name pretty much suggests what it does. what does a drawer do!? it has a handle which is used to drag the drawer container out...obviously ;)


First of all, I should say sorry for this wierd object I used for my drawer's handle ;) I couldn't find anything better!!
here is the XML which is being used to create what you saw above:

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="230dip" 
    android:id="@+id/frameLayout" 
    android:layout_gravity="bottom">
   <SlidingDrawer 
        android:layout_height="wrap_content"
        android:handle="@+id/handle" 
        android:content="@+id/content"
        android:id="@+id/slide" 
        android:orientation="vertical"
        android:layout_width="fill_parent">
   <ImageView 
        android:layout_width="55dip"
        android:layout_height="55dip" 
        android:id="@id/handle" 
        android:src="@drawable/arrow" />
  <LinearLayout 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:id="@id/content"
        android:orientation="vertical" 
        android:background="@drawable/wood01"
        android:padding="10dip">
     <Button 
         android:text="Test1" 
         android:id="@+id/Button01"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" />
     <Button 
         android:text="Test2" 
         android:id="@+id/Button02"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" />
     <Button 
         android:text="Test3" 
         android:id="@+id/Button03"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" />
   </LinearLayout>
  </SlidingDrawer>
</FrameLayout>

SlidingDrawer tag has two important attributes, android:handle and android:content; these attributes are actually references to other views which will be rendered as our drawer's handle and content. as you can see here we have two child views with the same id as specified for android:handle and android:content.

That's it. we are now familiar with two other useful Android widgets...

Custom selector android

GUI is always an important part of any application, because ordinary users dont know and don't care what's behind the scene; they want something easy to work with and nowadays attractive GUI is a must for most applications. although making an appealing and innovative interface needs something more than just programming skills and knowledge, every programmer should know how to customize different GUI components within whatever framework and environment they are working.

Today I'm gonna talk about one of the beautiful features of Android which gives you the ability to change the default behavior of GUI components. 
when designing GUIs, most of the times you want to change the appearance of buttons, input Fields, menus and.... Android Selectors have been provided to solve all these kind of problems, they enable us to decide what to show and how to show based on different states of each components...for example you can tell a button to have black background color with red text color when it is in pressed state or whatever else.

It is nothing but a simple ListView... believe me, and here is the XML which is being used to create it :

<ListView android:id="@+id/list" 
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" 
      android:dividerHeight="0dip"
      android:divider="@null" 
      android:listSelector="@drawable/list_selector"
      android:layout_gravity="center" />
the code which I've used to populate the list :

  ListView view = (ListView)findViewById(R.id.list);
  view.setAdapter(new ArrayAdapter(this, R.layout.menu_item, ITEMS));
  view.setOnItemClickListener(this); 
   
and finally, here is the content of menu_item.xml file :

<?xml version="1.0" encoding="utf-8"?>
 <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:textSize="12dip"
           android:textStyle="bold"
           android:paddingTop="20dip"
           android:paddingBottom="20dip"
           android:layout_gravity="center" 
           android:gravity="center"
           android:background="@drawable/selector"
           android:textColor="@drawable/color_selector"/>: 

see? it's a simple, ordinary list, there is no secret here but a simple trick; I've used selectors for both background and text color for our TextView, what do you think "selector" and "color_selector" are?
they actually refer to selector.xml and color_selector.xml files inside drawable directory, you can see the content of them below : 


<selector xmlns:android="http://schemas.android.com/apk/res/android">:
    <item android:state_selected="true" android:drawable="@drawable/selector_s" />:
    <item android:state_pressed="true" android:drawable="@drawable/selector_s" />:
    <item android:drawable="@drawable/selector_d" />:  
</selector>:
<selector xmlns:android="http://schemas.android.com/apk/res/android">:
    <item android:state_selected="true" android:color="@color/black" />:
    <item android:state_pressed="true" android:color="@color/red" />:
    <item android:color="@color/white" />:  
</selector>:

what does the content of color_selector file mean? it says that the text color will be black in "selected" state, red in "pressed" state and white otherwise, and i reckon now you should be able to figure out what the content of selector file means. 
here is the content of selector_s and selector_d :

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/pill"
    android:gravity="center" />
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/pill_s"
    android:gravity="center" />

as you might have noticed,I've also used "listSelector" attribute of our ListView to customize the behavior of the list when user is going through options in the list. 
list_selector.xml file looks like this : 

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@drawable/wood01" />
    <item android:drawable="@drawable/wood02" />  
</selector> 

and here are all the drawable objects i used in this application if you wanna give it a try and see how easy it works ;)