Search This Blog

Tuesday, November 1, 2011

SAX Parsing

SAX (Simple API for XML) is an event based sequential access parser API which provides mechanism for reading data from an XML document. This parser is used as alternative for DOM (Document Object Model) which operates on the document as a whole, where as SAX parsers operate on each piece of the XML document sequentially.

Here I am going to use this SAX Parser API to get some information from the server using Wi-fi Connectivity and displaying the value on Tablet/Phone powered by Android 2.x.

Design of Application

In this Application there is no much needed any sorts of decorations and here we use just a label to display the parsed value
 
  <?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
  <TextView android:id="@+id/DisplayValue" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" />
  </LinearLayout>
 
Main Activity
 
This class displays parsed value retrieved from URL and this class will throw exception if there is no net connectivity So add this module in this activity to check for internet connectivity
public boolean hasInternet(Context con) {
            NetworkInfo info = (NetworkInfo) ((ConnectivityManager) con
                    .getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info == null || !info.isConnected())
                return false;
            return true;
        }


package com.parsesample.parser;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class ParsingXML extends Activity {
    /** Called when the activity is first created. */
    TextView parseValue;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
               
        parseValue=new TextView(this);
        try {
           URL url = new URL("http://xxx.yyy.zzz.abc:qwe/yyy.xml");
            SAXParserFactory saxFactory=SAXParserFactory.newInstance();
            SAXParser parser=saxFactory.newSAXParser();
            XMLReader reader=parser.getXMLReader();
            XMLHandler handler=new XMLHandler();
            reader.setContentHandler(handler);
            reader.parse(new InputSource(url.openStream()));
            ParseDataSet dataSet=handler.getParsedData();
            parseValue.setText(dataSet.toString());
        } catch (Exception e) {
            //parseValue.setText("Error:  "+e.getMessage());
            Log.e("Exception Caught", e.getMessage());
        }
        setContentView(parseValue);
    }
}
 
Parser Class
 
This class handles parsing functionality of data from XML
 
/**
 *
 */
package com.parsesample.parser;

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

/**
 * @author venkat
 *
 */
public class XMLHandler extends DefaultHandler {

    protected boolean in_outertag = false;
    protected boolean in_innertag = false;
    protected boolean in_mytag = false;
    protected boolean version = false;

    private ParseDataSet dataSet = new ParseDataSet();

    public ParseDataSet getParsedData() {
        return this.dataSet;
    }

    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        this.dataSet = new ParseDataSet();
    }

    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        if (localName.equals("outertag")) {
            this.in_outertag = true;
        } else if (localName.equals("innertag")) {
            this.in_innertag = true;
        } else if (localName.equals("mytag")) {
            this.in_mytag = true;
        } else if (localName.equals("currentversion")) {
            this.version=true;
        } else if (localName.equals("tagwithnumber")) {
            String atrValue = attributes.getValue("thenumber");
            Integer i = Integer.parseInt(atrValue);
            dataSet.setExtractedInt(i);
        }
        super.startElement(uri, localName, qName, attributes);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        if (localName.equals("outertag")) {
            this.in_outertag = false;
        } else if (localName.equals("innertag")) {
            this.in_innertag = false;
        } else if (localName.equals("mytag")) {
            this.in_mytag = false;
        } else if (localName.equals("currentversion")) {
            this.version=false;
        }
        super.endElement(uri, localName, qName);
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        if (this.in_mytag) {
            // dataSet.setExtractedString(new String(ch,start,length));
            dataSet.setExtractedString(new String(ch));
        } else if (this.version) {
            dataSet.setExtractedString(new String(ch));
        }
        super.characters(ch, start, length);
    }
}
 
Parser Data Set
 
This POJO handles parser value and returns to Handler class
 
package com.parsesample.parser;

import android.util.Log;

public class ParseDataSet {
   
    private String extractedString = null;
    private int extractedInt = 0;

    public String getExtractedString() {
            return extractedString;
    }
    public void setExtractedString(String extractedString) {
            this.extractedString = extractedString;
    }

    public int getExtractedInt() {
            return extractedInt;
    }
    public void setExtractedInt(int extractedInt) {
            this.extractedInt = extractedInt;
    }
  
    public String toString(){
            Log.d("Extracted String   ->>>>", this.extractedString);
           /* return "ExtractedString = " + this.extractedString
                            + "nExtractedInt = " + this.extractedInt;*/
            return this.extractedString;
    }

}










Wednesday, March 16, 2011

Database Demo

Here I am sharing code for using Database (SQLite) in android and I hope this post will be useful for newbees to learn android widgets.


Here I am going to use Expandable List view to populate Table Values to Activity.

This Sample is Developed in Android 2.3.3 SDK.


main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView android:layout_height="wrap_content"
android:id="@+id/Name"
android:layout_width="fill_parent"
android:text="Name">
</TextView>

<EditText android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/EmpName"
android:inputType="text|textCapCharacters|textCapWords|textCapSentences|textAutoCorrect|textAutoComplete">
</EditText>

<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/Age"
android:text="Age">
</TextView>

<EditText android:layout_height="wrap_content"
android:id="@+id/EmpAge"
android:inputType="number|numberSigned|numberDecimal"
android:layout_width="fill_parent">
</EditText>

<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/RelativeLayout">

<Button android:text="InsertValues"
android:id="@+id/AddDet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10px">
</Button>

<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_toRightOf="@+id/AddDet"
android:text="ViewDetails"
android:id="@+id/ViewDet">
</Button>

</RelativeLayout>


</LinearLayout>




Main Activity (SQLiteTest.java)

This activity gets details from user and popups an alert dialog for successfull/failure in DB insertion and toast for the value inserted in DB. When user taps view details button displays Expandable list view activity.


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SQLiteTest extends Activity {
    /** Called when the activity is first created. */

    protected Button insertButton, viewButton;
    protected EditText nameText, ageText;
    DBHelper helper;
    Context mContext = this;
    String dispData;

   
    protected OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.AddDet) {
                Toast.makeText(
                        getApplicationContext(),
                        "Name  " + nameText.getText().toString() + "Age "
                                + ageText.getText().toString(),
                        Toast.LENGTH_LONG).show();
                Employee emp=new Employee(nameText.getText().toString(), Integer.parseInt(ageText.getText().toString()));
                int status =helper.insertTable(emp);
                if (status != -1) {
                    AlertDialog.Builder alert = new AlertDialog.Builder(
                            mContext);
                    alert.setMessage("Table Values Inserted");
                    alert.setNeutralButton("OK",
                            new DialogInterface.OnClickListener() {

                       
                       
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                    dialog.cancel();
                                }
                            });
                    AlertDialog al = alert.create();
                    al.show();
                } else {
                    AlertDialog.Builder alert = new AlertDialog.Builder(
                            mContext);
                    alert.setMessage("Table Values not Inserted");
                    alert.setNeutralButton("OK",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                    dialog.cancel();
                                }
                            });
                    AlertDialog ad = alert.create();
                    ad.show();
                }   
            } else if (v.getId() == R.id.ViewDet) {
                Intent intent=new Intent(SQLiteTest.this,sample.class);
                startActivity(intent);
            }

        }
    };

    protected void notifyTrigger(CharSequence Title, CharSequence msg) {
        CharSequence sequence = Title;
        CharSequence message = msg;
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.icon,
                "This is to Notify You", System.currentTimeMillis()) {
        };
        Intent notificationIntent = new Intent(this, SQLiteTest.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(getApplicationContext(), sequence,
                message, pIntent);
        nm.notify(1, notification);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        helper = new DBHelper(getApplicationContext());
        // helper.createTable();
        insertButton = (Button) findViewById(R.id.AddDet);
        viewButton = (Button) findViewById(R.id.ViewDet);
        nameText = (EditText) findViewById(R.id.EmpName);
        ageText = (EditText) findViewById(R.id.EmpAge);
        insertButton.setOnClickListener(onClickListener);
        viewButton.setOnClickListener(onClickListener);

              
    }
}


DBConnection Class (DBHelper.java)

This class creates Database and tables and inserts the value from the user input taken from POJO


import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteFullException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

    private static final String dbName = "SampleDB";
    public final String tableName="TestTable";
    public final String attribValue1="Name";
    public final String attribValue2="age";
    SQLiteTest sqltest;
    String[] nameVal;
    int[] ageVal;
    int size;
    int i=0;
   
    public DBHelper(Context context) {
        super(context, dbName, null, 33);
        sqltest = new SQLiteTest();
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String sql="";
        try {
            //sql ="create table if not exists " + tableName + "(" +attribValue1 + "varchar" + attribValue2+ "int(3))";
            sql="CREATE TABLE "+tableName+"(Name TEXT,age INTEGER)";
            db.execSQL(sql);
        } catch(SQLiteFullException e) {
            e.getMessage();
            Log.d("Test", sql);   
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
   
    public void createTable() {
        SQLiteDatabase db=this.getWritableDatabase();
        String query = "create table if not exists " + tableName + "("+ attribValue1 + "varchar(20)" + attribValue2    + "int(3))";
        db.execSQL(query);
        db.close();
    }
   
    public int insertTable(Employee emp){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put("Name",emp.getName());
        cv.put("age", emp.getAge());
        int status=(int) db.insert(tableName, null, cv);
        db.close();
        return status;   
    }
   
    public List viewTable() {
        //String result="";
        List arrList=new ArrayList ();
        try {
            SQLiteDatabase db=this.getWritableDatabase();
            String query="select * from " + tableName;
            Log.d("query message  ", query);
            Cursor c = db.rawQuery(query, null);
             size=c.getCount();
            nameVal=new String[size];
            ageVal=new int[size];
           
            int col1 = c.getColumnIndex("Name");
            int col2 = c.getColumnIndex("age");
           
            c.moveToFirst();
            if (c != null) {
                do {
                    nameVal[i]=c.getString(col1);
                    ageVal[i]=c.getInt(col2);
                   
                   
                    //arrList.add(ageVal[i]+"");
                    //result=result+nameVal+" "+ageVal+" ";
                    System.out.println("Name     :"+nameVal[i]);
                    System.out.println("Age      :"+ageVal[i]);
                    i++;
                } while (c.moveToNext());
                arrList.add(nameVal);
                arrList.add(ageVal);
            }
           
            db.close();
        }catch(SQLiteFullException exp) {
             exp.getMessage();
             Log.d("Exception Cause", exp.getMessage());
         }
       
        return arrList;
       
    }

}



POJO for DB(Employee.java)

A POJO is simply a Java object that does not implement any special interfaces which is used to design simple Business Domains.

public class Employee {
   
    int _age;
    String _name;
   
    public Employee(String Name,int Age)
    {
        this._name=Name;
        this._age=Age;
    }
   
    public String getName()
    {
        return this._name;
    }
   
    public int getAge()
    {
        return this._age;
    }
   
    public void setName(String Name)
    {
        this._name=Name;
    }
    public void setAge(int Age)
    {
        this._age=Age;
    }
   

}


Activity to populate table values in Expandable List View


This Activity disaplays Expandable Listview that displays populated table values.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.widget.ExpandableListAdapter;
import android.widget.SimpleExpandableListAdapter;

public class sample extends ExpandableListActivity {
    private static final String NAME = "NAME";
    DBHelper helper;
    List dispData;
    Iterator it;
   
    String[] data;
    String[] name;
    int[] age;
    private ExpandableListAdapter mAdapter;
   
      
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        helper = new DBHelper(getApplicationContext());
        dispData=helper.viewTable();

        name=new String[dispData.size()];
       
        name=(String[])dispData.get(0);
        age=(int[]) dispData.get(1);
        for(int i=0;i<name.length;i++)
        {
            System.out.println("New data :"+name[i]);
        }
       
       /* data=new String[dispData.size()];
        it=dispData.iterator();
        i=0;
        while(it.hasNext()) {
            String value=it.next().toString();
            data[i]=value;
            i++;
        }*/
      
           
        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 < name.length; i++) {
            Map<String, String> curGroupMap = new HashMap<String, String>();
            groupData.add(curGroupMap);
            curGroupMap.put(NAME,"" +name[i]);
        
            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
         
                Map<String, String> curChildMap = new HashMap<String, String>();
                children.add(curChildMap);
                curChildMap.put(NAME,"" +age[i]);
                                 
            childData.add(children);
          
        }
       
        // Set up our adapter
        mAdapter = new SimpleExpandableListAdapter(
                this,
                groupData,
                android.R.layout.simple_expandable_list_item_1,
                new String[] { NAME },
                new int[] { android.R.id.text1 },
                childData,
                android.R.layout.simple_expandable_list_item_2,
                new String[] { NAME },
                new int[] { android.R.id.text1 }
                );
        setListAdapter(mAdapter);
    }
    }