Monday, October 29, 2012

Android ActionBar Example

Hi developers, here the simple example for the action bar control android.

menu_ctrl.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item

        android:id="@+id/menuitem1"
        android:showAsAction="always"
        android:title="Add">
    </item>
    <item
        android:id="@+id/menuitem2"
        android:showAsAction="always"
        android:title="Sub">
    </item>
    <item
        android:id="@+id/menuitem3"
        android:showAsAction="always"
        android:title="Mul">
    </item>
    <item
        android:id="@+id/menuitem4"
        android:showAsAction="always"
        android:title="Div">
    </item>

</menu>


main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="20dp" >

        <TextView

            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/str_firstnumber"
            android:textSize="15dp" />

        <EditText

            android:id="@+id/FirstNumberET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number" />
    </LinearLayout>

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp" >

        <TextView

            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/str_secnumber"
            android:textSize="15dp" />

        <EditText

            android:id="@+id/SecondNumberET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number" />
    </LinearLayout>

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp" >

        <TextView

            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/str_answer"
            android:textSize="15dp" />

        <EditText

            android:id="@+id/AnswerET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:editable="false"
            android:inputType="numberSigned"
            android:textColor="#FF0000" />
    </LinearLayout>

</LinearLayout>


MainActivity.java



public class MainActivity extends Activity 
{
private EditText etFirstName, etSecondName, etAnswer;
private Double intAns;

@Override

public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Initialisation();
}

public void Initialisation() 

{
etFirstName = (EditText) findViewById(R.id.FirstNumberET);
etSecondName = (EditText) findViewById(R.id.SecondNumberET);
etAnswer = (EditText) findViewById(R.id.AnswerET);
}

@Override

public boolean onCreateOptionsMenu(Menu menu) 
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_ctrl, menu);
return true;
}

@Override

public boolean onOptionsItemSelected(MenuItem item) 
{
switch (item.getItemId()) 
{
case R.id.menuitem1:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
+ (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

case R.id.menuitem2:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
- (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

case R.id.menuitem3:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
* (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

case R.id.menuitem4:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
/ (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

default:

break;
}
return true;
}
}


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