Constant Contact Labs Developer Blog

  • Parsing XML on Android Posted Wednesday, December 2, 2009 Huan Lai 25 Comments

    Parsing XML on Android

    Parsing XML from the internet is a pretty common requirement on any platform. There are numerous ways to accomplish this task on every language out there, and the Android platform is no exception. On the Android, this is accomplished using SAXParser, a serial access parser API for XML. SAXParser functions as a stream parser, with an event-driven API, using callback methods that trigger everytime events occur during the reading.

    The majority of the work is done by a SAX-Handler. The SAXParser will walk through the XML file from beginning to end (hence parsing is always unidirectional) and calls appropriate handler methods along the way. For this exercise, we will create a Handler that extends org.xml.sax.helpers.DefaultHandler and overrides the necessary methods.

    On the start/end of each document, the following methods get called:

    public void startDocument() throws SAXException {} 
    public void endDocument() throws SAXException {}
    

    When the Parser reaches an opening tag, like <exampletag name=“labs”>, the following method gets called:

    public void startElement(String namespaceURI, String localName, String qName, 
        Attributes atts) throws SAXException {}
    

    In this case, localName will be "exampletag". The atts variable will hold any associated attribute information: atts.getValue("name") will return "labs".

    When we reach a closing tag, like </exampletag>, the equivalent closing method gets called:

    public void endElement(String namespaceURI, String localName, String qName) 
        throws SAXException {}
    

    In the same manner, localName will be "exampletag".

    In between an opening and closing tag, there can be a string, like <exampletag>here is some content</exampletag>. The SAXParser reads in the string, one character at a time, but buffers method calls to the handler:

    public void characters(char ch[], int start, int length) {}
    

    The ch[] array holds a buffer of characters that the SAXParser has read in, but the only relevant chunk is given by the start and length values. With large enough strings, the characters() method may be called multiple times within a single block of character data. This is a place where I personally stumbled with, as it seems many tutorials out there seem to ignore this fact, assuming the entire block is returned and end up only getting partial data.

    Now that I've explained the basics of how this all works, here is some very basic example code that parses an XML doc for content of "qwerasdf" elements:
    Creating a SAXParser and give it a handler:

    /* Create a URL we want to load some xml-data from. */
    URL url = new URL("http://example.com/example.xml");
    
    /* Get a SAXParser from the SAXPArserFactory. */
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    
    /* Get the XMLReader of the SAXParser we created. */
    XMLReader xr = sp.getXMLReader();
    /* Create a new ContentHandler and apply it to the XML-Reader*/
    ExampleHandler myExampleHandler = new ExampleHandler();
    xr.setContentHandler(myExampleHandler);
    
    /* Parse the xml-data from our URL. */
    xr.parse(new InputSource(url.openStream()));
    /* Parsing has finished. */ 
    

     

     
     
    Definition of the ExampleHandler:

    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler; 
    
    public class ExampleHandler extends DefaultHandler { 
        StringBuffer buff = null;
        boolean buffering = false; 
        
        @Override
        public void startDocument() throws SAXException {
            // Some sort of setting up work
        } 
        
        @Override
        public void endDocument() throws SAXException {
            // Some sort of finishing up work
        } 
        
        @Override
        public void startElement(String namespaceURI, String localName, String qName, 
                Attributes atts) throws SAXException {
            if (localName.equals("qwerasdf")) {
                buff = new StringBuffer("");
                buffering = true;
            }   
        } 
        
        @Override
        public void characters(char ch[], int start, int length) {
            if(buffering) {
                buff.append(ch, start, length)
            }
        } 
        
        @Override
        public void endElement(String namespaceURI, String localName, String qName) 
        throws SAXException {
            if (localName.equals("blah")) {
                buffering = false; 
                String content = buff.toString();
                
                // Do something with the full text content that we've just parsed
            }
        }
    }
    

     

     
    The opinions expressed here represent those of the author and not those of Constant Contact, Inc. Read Blog Terms

    Tags

    AndroidMobilePlatformsXML
    Next Post Previous Post
     

Comments (25) +comment on this post
 

  • Stelios Charmpalis | 5:01 AM October 6, 2010

    Have you a tutorial on how can we produce a Custom ListView with the elements that you’re taking from the XML after the parsing?

  • Jim Garretson | 7:52 AM October 6, 2010

    Hi Stellos, We don’t have a tutorial ourselves, but if you’d like you can take a look at the source to our Android app here:
    http://qvandroid.svn.sourceforge.net/viewvc/qvandroid/

  • Tyler | 8:35 PM December 16, 2010

    Hello,

    Your code example is working great so far, thanks! However…

    I am receiving this error:

    ===============

    The method startElement(String, String, String, Attributes) of type DefaultHandler must override or implement a supertype method

    ===============

    After much searching around, everyone suggests making sure that the Eclipse (and the project specific settings) Java Compiler is set to compiler compliance level 1.6. I have done both of these things and yet the problem persists…

    Any Ideas?

  • Tyler | 1:28 AM December 17, 2010

    Hello,

    And a few hours later I found what my problem was. I was using an incorrect import on the SAX Attributes. Skipping between your tutorial and another, and I constantly overlooked the simple “make sure all your imports are correct”... unfortunately a ctrl+shift+o didn’t fix it… but making sure I had the following imports, I was all set:

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

    Just like your tutorial says wink Thanks!

  • Jim Garretson | 10:10 AM December 17, 2010

    Hi Tyler,

    I’m happy you were able to figure out the problem! Although the compiler compliance level is a pretty common source of errors like that, it can otherwise be tricky to debug. Thanks for coming back and letting us know how you solved it!

  • Joemarie Amparo | 5:04 AM February 21, 2011

    Hello,

    I’ve been trying to parse the xml response through HttpResponse but I can’t get it done. Can anybody help me get through this. Here’s my code:

    text = (TextView)findViewById(R.id.text);
    HttpURLConnection conn;
    boolean result = false;


    BufferedReader lResultReader = null;
    try {
    URI lUri = new URI(“http://api.groupjump.com/authentication.php?method=login&apikey=1111111111&username=1@1.com&password=1111111”);

    // Prepares the request.
    HttpClient lHttpClient = new DefaultHttpClient();
    HttpGet lHttpGet = new HttpGet();
    lHttpGet.setURI(lUri);

    // Sends the request and read the response
    HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
    InputStream lInputStream = lHttpResponse.getEntity().getContent();


    /* Get a SAXParser from the SAXPArserFactory. */
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    /* Get the XMLReader of the SAXParser we created. */
    XMLReader xr = sp.getXMLReader();

    /* Create a new ContentHandler and apply it to the XML-Reader*/
    ExampleHandler myExampleHandler = new ExampleHandler();
    xr.setContentHandler(myExampleHandler);


    //this is where i get error. Any alternative ways please:
    xr.parse(new InputSource(lTmpResult));

    /* Parsing has finished. */
    /* Our ExampleHandler now provides the parsed data to us. */
    ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
    /* Set the result to be displayed in our GUI. */
    text.append(parsedExampleDataSet.toString());
    }
    catch(MalformedURLException e){
    text.setText(“1: “+e.getMessage());
    e.printStackTrace();
    }
    catch(IOException e){
    e.printStackTrace();
    text.setText(“2: “+e.getMessage());
    }
    catch(Exception e){
    e.printStackTrace();
    text.setText(“3: “+e.getMessage());
    }

    I get error on this line:

    xr.parse(new InputSource(lTmpResult));

    Here is the XML format that I want to parse.
    <?xml version=“1.0”?>
    <callback>
    <request>
    <authentication>
    <status> </status>
    <message></message>
    <content>
    <id> </id>
    <sessionkey></sessionkey>
    </content>
    </authentication>
    </request>
    </callback>

    Please help.

    Thanks,
    Joemarie Amparo

  • nehal | 7:26 AM March 22, 2011

    Hi Joemarie Amparo:
    try this
    xr.parse(new InputSource(lTmpResult.toString()));

  • Jeff | 4:24 PM April 21, 2011

    Hi, I’m trying to parse an XML response from an API but I’m getting stuck. Here is what I’ve done so far


    package my.example;

    import java.io.IOException;

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

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;

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

    public class ParseExample extends Activity {
     
      TextView tv;
      String line;
     
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
         
         
              //Http request
            try {
              HttpClient hclient = new DefaultHttpClient();
              HttpGet get = new HttpGet(“http://www.google.com/ig/api?weather=Cardiff”);
              HttpResponse hrep = hclient.execute(get);
              HttpEntity httpEntity = hrep.getEntity();
             
              //passing the result into a string
              line = EntityUtils.toString(httpEntity); 
             
             
              //setting up XML parser
              SAXParserFactory saxpf = SAXParserFactory.newInstance();
              SAXParser saxp = saxpf.newSAXParser();
             
              XMLReader xr = saxp.getXMLReader();
             
              ExHandler myHandler = new ExHandler();
              xr.setContentHandler(myHandler);
             
              // passing the string into the parser
              xr.parse(new InputSource(line));
             
            } catch (ClientProtocolException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (ParseException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (ParserConfigurationException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (SAXException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
      }
       
      }
    }

    For the Handler class here is what I’ve done

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

    public class ExHandler extends DefaultHandler {
     
      StringBuffer buffer = null;
      Boolean buffering = false;
     
      @Override
      public void startDocument() throws SAXException {
         
      }

      @Override
      public void endDocument() throws SAXException {

      }

      @Override
      public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
         
      }
     
     
     

    }

    I’m stuck here because I need to understand a couple of things;

    1. What settings would I do at startDocument?

    2. Do I need to pass in values for uri?

    3. My target XML file looks like this

    <xml_api_reply version=“1”>

    <weather module_id=“0” tab_id=“0” mobile_row=“0” mobile_zipped=“1” row=“0” section=“0”>
    <forecast_conditions>
    <day_of_week data=“Sun”>
    <low data=“48”>
    <high data=“64”>
    <condition data=“Clear”>
    </forecast_conditions>
    </weather>
    </xml_api_reply>

    how would I get data from the <condition>

  • Joel | 5:06 AM April 27, 2011

    Hi, I have a problem. I keep getting the Error:null using String str = buff.append(ch,start,length).toString() in characters method. Then in the getter/setter class I have a line: return “extractedString=” + this.extractedString.trim();
    Can you please help me?

  • jesi | 2:37 AM May 17, 2011

    can you help me parse this xml file, i need the code for this . i am new to android and java

    <Quiz>
    - <Topics id=“1” Topicname=“Essentials”>
    - <Question number=“1” title=“True or False: Compasses always point to true north.”>
      <Option Number=“A” title=“True” >
      <Option Number=“B” title=“False” correct=“True” description=“False, compasses point to magnetic north � the difference varies between where you are in the world.” >
      </Question>
    - <Question number=“2” title=“If the moon rises before the sun has set, the illuminated side faces this direction:”>
      <Option Number=“A” title=“North” >
      <Option Number=“B” title=“South” >
      <Option Number=“C” title=“West” correct=“True” description=“The illuminated side of the moon always points west.” >
      <Option Number=“D” title=“East” >
      </Question>
    - <Question number=“3” title=“The stars passage over the horizon starts ___ minutes earlier each night.”>
      <Option Number=“A” title=“Two minutes” >
      <Option Number=“B” title=“Four minutes” correct=“True” description=“The stars passage over the horizon starts 4 minutes earlier each night.” >
      <Option Number=“C” title=“Six minutes” >
      <Option Number=“D” title=“Eight minutes” >
      </Question>
    - <Question number=“4” title=“True or False: There is no equivalent of the pole star near the South Celestial Pole.”>
      <Option Number=“A” title=“True” correct=“True” description=“True, there is no equivalent of the pole star in the South Pole. However the southern cross provides a signpost to the south.” >
      <Option Number=“B” title=“False” >
      </Question>
    - <Question number=“5” title=“True or False: The higher the clouds, the finer the weather.”>
      <Option Number=“A” title=“True” correct=“True” description=“True, high clouds indicate the dry air and high pressure of fair weather.” >
      <Option Number=“B” title=“False” >
      </Question>
    - <Question number=“6” title=“Which of the following is NOT true:”>
      <Option Number=“A” title=“A red sky in the morning indicates that a storm is approaching” >
      <Option Number=“B” title=“A grey morning heralds a dry day” >
      <Option Number=“C” title=“A grey evening sky means that rain is imminent” >
      <Option Number=“D” title=“A violet sky in the morning indicates fair weather” correct=“True” description=“A violet sky in the morning does NOT indicate fair weather.” >
      </Question>
    - <Question number=“7” title=“True or False: Curly haired people find their hair becomes unmanageable and tight as bad weather approaches.”>
      <Option Number=“A” title=“True” correct=“True” description=“True, curly haired people find their hair becomes tight and unmanageable as bad weather approaches.” >
      <Option Number=“B” title=“False” >
      </Question>
    - <Question number=“8” title=“Which of the following is NOT a valid weather predicting device:”>
      <Option Number=“A” title=“A rainbow in the afternoon is a sign of good weather” >
      <Option Number=“B” title=“A corona around the moon enlarges if fair weather lies ahead” >
      <Option Number=“C” title=“Insect-eating birds fly lower when a storm is approaching” >
      <Option Number=“D” title=“Unusual mammal activity at night often indicates coming rainfall” correct=“True” description=“Unusual mammal activity at night is NOT an indication of coming rainfall” >
      </Question>
    - <Question number=“9” title=“How long does it take for eyes to become adjusted to darkness?”>
      <Option Number=“A” title=“5 - 10 minutes” >
      <Option Number=“B” title=“15 - 25 minutes” >
      <Option Number=“C” title=“30 - 40 minutes” correct=“True” description=“It takes 30 - 40 minutes for eyes to adjust to darkness” >
      <Option Number=“D” title=“45 - 55 minutes” >
      </Question>
    - <Question number=“10” title=“When on the move, babies and small children should be:”>
      <Option Number=“A” title=“Secured onto an adult’s back” >
      <Option Number=“B” title=“Carried papoose style” correct=“True” description=“Babies and small children should be carried papoose style while on the move” >
      <Option Number=“C” title=“Supported on an adult’s shoulders” >
      <Option Number=“D” title=“Pushed in makeshift sleds” >
      </Question>
    - <Question number=“11” title=“River currents are the fastest:”>
      <Option Number=“A” title=“On the inside of bends” >
      <Option Number=“B” title=“On the outside of bends” correct=“True” description=“River currents are fatest on the outside of bends” >
      <Option Number=“C” title=“Near waterfalls” >
      <Option Number=“D” title=“Near the ocean” >
      </Question>
    - <Question number=“12” title=“Almost any signal repeated ____ times will serve as a distress signal.”>
      <Option Number=“A” title=“3” >
      <Option Number=“B” title=“5” >
      <Option Number=“C” title=“6” correct=“True” description=“Signals repeated 6 times will serve as a distress signal” >
      <Option Number=“D” title=“9” >
      </Question>
      </Topics>

  • Programmer XR | 4:18 AM May 23, 2011

    Thanks for this explanation about SAX parsing, here is another tutorial about XML parsing in Android. But that one is based around converting the XML to a Document. Here is a link:

    http://p-xr.com/android-tutorial-how-to-parseread-xml-data-into-android-listview/

  • lucki | 8:18 PM December 27, 2011

    i’m new in android and i have to parse this xml data wht can i do for tht
    <data>
    - <galaries>
      <galaryid>gly117L6xuN</galaryid>
      <galaryName>first</galaryName>
      <galarytype>Free</galarytype>
      <galarydescription>free set of images</galarydescription>
      <galaryCover>http://youmakethepage.com/wall/server/uploads/gly117L6xuN/7428s613kd92ab.jpg</galaryCover>
      </galaries>
    - <galaries>
      <galaryid>gly462UcL8q</galaryid>
      <galaryName>second</galaryName>
      <galarytype>Paid</galarytype>
      <galarydescription>paid gallary</galarydescription>
      <galaryCover>http://youmakethepage.com/wall/server/uploads/gly462UcL8q/23549ja516jzuo9.jpg</galaryCover>
      </galaries>
    - <galaries>
      <galaryid>gly346J4Gkr</galaryid>
      <galaryName>third</galaryName>
      <galarytype>Paid</galarytype>
      <galarydescription>test</galarydescription>
      <galaryCover>http://youmakethepage.com/wall/server/uploads/gly346J4Gkr/20500hz8fyqrqt1.jpg</galaryCover>
      </galaries>
    - <galaries>
      <galaryid>gly2441Y4pu</galaryid>
      <galaryName>forth</galaryName>
      <galarytype>Paid</galarytype>
      <galarydescription>description</galarydescription>
      <galaryCover>http://youmakethepage.com/wall/server/uploads/gly2441Y4pu/33156v7euvudhpr.jpg</galaryCover>
      </galaries>
    - <galaries>
      <galaryid>gly28OLNAI</galaryid>
      <galaryName>fifth</galaryName>
      <galarytype>Paid</galarytype>
      <galarydescription>test</galarydescription>
      <galaryCover>http://youmakethepage.com/wall/server/uploads/gly28OLNAI/3828175vee6crbj.jpg</galaryCover>
      </galaries>
    - <galaries>
      <galaryid>gly581PORDL</galaryid>
      <galaryName>sixth</galaryName>
      <galarytype>Paid</galarytype>
      <galarydescription>description</galarydescription>
      <galaryCover>http://youmakethepage.com/wall/server/uploads/gly581PORDL/horses208.jpg</galaryCover>
      </galaries>
      </data>

  • Arun Badole | 2:08 AM March 31, 2012

    Hi Huan Lai
      Thanks for this helpfull blog.I am working on applications which needs lots of XML Parsing.And I use the same way as you have taught us in this blog for parsing.But my problem is that where should I save the parsed data.
    Right now what I am doing is I parse the data and save that data in static ArrayList or HashMap variables.So whenever I need that data I directly uses the static variables and show to my ListView or wherever I needed.And it works fine most of the time.
    But what exactly problem I am facing is when I switch to some other app like Browser so I lost my previous apps data (static variable which I initilaized by parsing XMLs).So in such cases how can I retain my app’s status.


    Please Help

  • paras | 3:24 PM May 1, 2012

    Thanks for the post, It really helped me a lot,i was stuck on xml parsing earlier but after reading it,did it smoothly
    thanks

  • Yok | 5:12 AM July 27, 2012

    sappi

  • pinky | 11:55 AM September 5, 2012

    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.widget.LinearLayout;
    import android.widget.TextView;

    public class XMLParser2Activity extends Activity {
     
      SiteLists sitesList = null;
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
         
         
          LinearLayout layout=new LinearLayout(this);
          layout.setOrientation(1);
       
         
          /** Create a new textview array to display the results */
          TextView name[];
          TextView website[];
          TextView category[];

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

            /** Send URL to parse XML Tags */
            URL sourceUrl = new URL(
                  “http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml”);

            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            MyHandler myXMLHandler = new MyHandler();
            xr.setContentHandler(myXMLHandler);
           
            xr.parse(new InputSource(sourceUrl.openStream()));
           
           
          //////////////////////////////////////////////////////// 
            /*Set the XML Content  
            Type 1:
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(parseContent));

            Type 2:
                URL url = new   URL(“http://www.DOMAON.com/File.xmll”);
             
             
            Parser the XML
                xr.parse(is); [For type1]
                xr.parse(new InputSource(url.openStream())); [For type2]
            */
        //////////////////////////////////////////////////////////////////// 
           
           
           
           
          } catch (Exception e)
          {
            System.out.println(“XML Pasing Excpetion = ” + e);
          }

          /** Get result from MyXMLHandler SitlesList Object */
          sitesList = MyHandler.sitesList;

          /** Assign textview array lenght by arraylist size */
          name = new TextView[sitesList.getName().size()];
          website = new TextView[sitesList.getName().size()];
          category = new TextView[sitesList.getName().size()];

          /** Set the result text in textview and add it to layout */
          for (int i = 0; i < sitesList.getName().size(); i++)
          {
            name = new TextView(this);
            name.setText(“Name = “+sitesList.getName().get(i));
            name.setTextSize(25);
           
            website = new TextView(this);
            website.setText(“Website = “+sitesList.getWebsite().get(i));
            website.setTextSize(25);
           
            category = new TextView(this);
            category.setText(“Website Category = “+sitesList.getCategory().get(i));
            category.setTextSize(25);
           
            layout.addView(name);
            layout.addView(website);
            layout.addView(category);
          }

          /** Set the layout view to display */
          setContentView(layout);

       
      }
    }

    handeler class

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

    public class MyHandler extends DefaultHandler
    {
      Boolean currentElement = false;
      String currentValue = null;
      public static SiteLists sitesList = null;

      public static SiteLists getSitesList()
      {
          return sitesList;
         
      }

      public static void setSitesList(SiteLists sitesList) {
          MyHandler.sitesList = sitesList;
      }

      /** Called when tag starts ( ex:- <name>AndroidPeople</name>
        *—<name> )*/
      @Override
      public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException
    {

          currentElement = true;

          if (localName.equals(“maintag”))
          {
            /** Start */
            sitesList = new SiteLists();
          }
          else if (localName.equals(“website”))
          {
            /** Get attribute value */
            String attr = attributes.getValue(“category”);
            sitesList.setCategory(attr);
          }

      }

      /** Called when tag closing ( ex:- <name>AndroidPeople</name>
        *—</name> )*/
      @Override
      public void endElement(String uri, String localName, String qName)
            throws SAXException
    {

          currentElement = false;

          /** set value */
          if (localName.equalsIgnoreCase(“name”))
            sitesList.setName(currentValue);
          else if (localName.equalsIgnoreCase(“website”))
            sitesList.setWebsite(currentValue);
      }

      /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
        *—to get AndroidPeople Character ) */
      @Override
      public void characters(char[] ch, int start, int length)
            throws SAXException {

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

      }

    }

    sitelist class
    package cb.parser;

    import java.util.ArrayList;

    public class SiteLists {

      /** Variables */
      private ArrayList<String> name = new ArrayList<String>();
      private ArrayList<String> website = new ArrayList<String>();
      private ArrayList<String> category = new ArrayList<String>();

     
      /** In Setter method default it will return arraylist
        *  change that to add */
     
      public ArrayList<String> getName() {
          return name;
      }

      public void setName(String name) {
          this.name.add(name);
      }

      public ArrayList<String> getWebsite() {
          return website;
      }

      public void setWebsite(String website) {
          this.website.add(website);
      }

      public ArrayList<String> getCategory() {
          return category;
      }

      public void setCategory(String category) {
          this.category.add(category);
      }


    }

  • pinky | 12:06 PM September 5, 2012

    DOM parser…

    package cb.domparsing;

    import java.net.URL;
    import java.util.ArrayList;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;

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

    public class XmlParsingDom1Activity extends Activity
    {
      /** Called when the activity is first created. */
      ArrayList<String> arr;
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
         
          TextView text1=(TextView)findViewById(R.id.textView1);
          //text1.setText(“Data From DomXML”);
          //arr.add(“Data From DomXML”);
          try
          {
            System.out.println(“IN Try”);
            URL url=new URL(“http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml”);
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse(new InputSource(url.openStream()));
           
           
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName(“item”);
            System.out.println(“For come”);
            for (int i = 0; i < nodeList.getLength(); i++)
            {
              System.out.println(“For loop”);
              Node node = nodeList.item(i);
             
              Element fstElmnt = (Element) node;
              NodeList nameList = fstElmnt.getElementsByTagName(“name”);
              Element nameElement = (Element) nameList.item(0);
              nameList = nameElement.getChildNodes();
              text1.setText( ((Node) nameList.item(0)).getNodeValue());
              //arr.add(“Name = “+ ((Node) nameList.item(0)).getNodeValue());
              System.out.println(“CB Name “+ ((Node) nameList.item(0)).getNodeValue());
            }
          }
          catch(Exception e)
          {
            System.out.println(“Parsing Exception”+e);
          }
          //text1.setText((CharSequence) arr);
      }
    }

  • pinky | 1:43 PM September 5, 2012

    json parser:


    package com.pxr.tutorial.json;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.util.Log;

    public class JSONfunctions {

      public static JSONObject getJSONfromURL(String url){
          InputStream is = null;
          String result = “”;
          JSONObject jArray = null;
         
          //http post
          try{
              HttpClient httpclient = new DefaultHttpClient();
              HttpPost httppost = new HttpPost(url);
              HttpResponse response = httpclient.execute(httppost);
              HttpEntity entity = response.getEntity();
              is = entity.getContent();

          }catch(Exception e){
              Log.e(“log_tag”, “Error in http connection “+e.toString());
          }
         
        //convert response to string
          try{
              BufferedReader reader = new BufferedReader(new InputStreamReader(is,“iso-8859-1”),8);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                    sb.append(line + “\n”);
              }
              is.close();
              result=sb.toString();
          }catch(Exception e){
              Log.e(“log_tag”, “Error converting result “+e.toString());
          }
         
          try{
           
            jArray = new JSONObject(result);       
          }catch(JSONException e){
              Log.e(“log_tag”, “Error parsing data “+e.toString());
          }
     
          return jArray;
      }
    }

  • pinky | 2:05 PM September 5, 2012

    package com.pxr.tutorial.json;

    import java.util.ArrayList;
    import java.util.HashMap;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import com.pxr.tutorial.xmltest.R;

    import android.app.ListActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;

    public class Main extends ListActivity {
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.listplaceholder);
         
          ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
       
       
          JSONObject json = JSONfunctions.getJSONfromURL(“http://api.geonames.org/earthquakesJSON?north=44.1&south;=-9.9&east;=-22.4&west=55.2&username=demo”);
             
          try{
           
            JSONArray earthquakes = json.getJSONArray(“earthquakes”);
           
            for(int i=0;i<earthquakes.length();i++){               
              HashMap<String, String> map = new HashMap<String, String>(); 
              JSONObject e = earthquakes.getJSONObject(i);
             
              map.put(“id”,  String.valueOf(i));
              map.put(“name”, “Earthquake name:” + e.getString(“eqid”));
              map.put(“magnitude”, “Magnitude: ” +  e.getString(“magnitude”));
              mylist.add(map);       
            }     
          }catch(JSONException e)      {
            Log.e(“log_tag”, “Error parsing data “+e.toString());
          }
         
          ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
                    new String[] { “name”, “magnitude” },
                    new int[] { R.id.item_title, R.id.item_subtitle });
         
          setListAdapter(adapter);
         
          final ListView lv = getListView();
          lv.setTextFilterEnabled(true); 
          lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {         
              @SuppressWarnings(“unchecked”)
              HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);             
              Toast.makeText(Main.this, “ID ’” + o.get(“id”) + ”’ was clicked.”, Toast.LENGTH_SHORT).show();

            }
          });
      }
    }

  • pinky | 2:08 PM September 5, 2012

    package com.first;

    import java.util.ArrayList;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;

    public class Viewclass extends Activity{
     
     
          DBclass dbv;
          ListView lv1;
         
          @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.view);
           
            dbv = new DBclass(getApplicationContext());
            dbv.openDB();
           
            ArrayList details = dbv.getAllDetails();
            dbv.closeDB();
           
            lv1=(ListView)findViewById(R.id.ListView01);
            lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 ,details));
         
         
            }

    }

    ////////////////////////////////////
    package com.first;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Spinner;

    public class Update1class extends Activity {
      Button update1_back_button,update1_submit_button,update1_home_button;
         
      EditText update_name,update_age;
      RadioButton femalebutton1,malebutton1;
      RadioGroup group1;
      Spinner spinner1;
      DBclass dbcls;
      String studentname;
     
      String name_value1;
      int age_value1;
      String qualifications1;
      String clickitem1;
      //String Oldname;
          @Override
          public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.update1);
         
          update_name=(EditText)findViewById(R.id.updatename);
          update_age=(EditText)findViewById(R.id.updateage);
         
          dbcls=new DBclass(Update1class.this);
          dbcls.openDB();
         
          Bundle bundle=getIntent().getExtras();
          studentname=bundle.getString(“Name”);
          update_name.setText(studentname);
         
          update1_back_button=(Button)findViewById(R.id.updateback1);
          update1_home_button=(Button)findViewById(R.id.updatehome1);
          update1_submit_button=(Button)findViewById(R.id.updatesubmit1);
         
          femalebutton1=(RadioButton)findViewById(R.id.updateRadioButton1);
          malebutton1=(RadioButton)findViewById(R.id.updateRadioButton2);
         
          group1=(RadioGroup)findViewById(R.id.radiogroup1);
         
          spinner1=(Spinner)findViewById(R.id.updateSpinner2);
          String[] qualifications =new String[]{“BE”,“MSC”,“MCOM”,“BBM”,“BCOM”,“BCA”,“MBA”,“MTEC”,“MS”};
          spinner1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,qualifications));
         
          update1_home_button.setOnClickListener(update1home);
          update1_back_button.setOnClickListener(update1back);
          update1_submit_button.setOnClickListener(update1submit);
      }
     
      OnClickListener   update1back =new OnClickListener() {
         
          @Override
          public void onClick(View v) {
            Intent intent=new Intent(Update1class.this,Updateclass.class);
            startActivity(intent);
           
          }
      };
      OnClickListener   update1home =new OnClickListener() {
         
          @Override
          public void onClick(View v) {
            Intent intent=new Intent(Update1class.this,Homeactivity.class);
            startActivity(intent);
           
          }
      };

        OnClickListener   update1submit=new OnClickListener() {
         
          @Override
          public void onClick(View v) {
           
           
           
            Boolean flag=false;
            //gender
            clickitem1=” “;
            Log.i(“VALUE OF clickitem1 (global)”,clickitem1);
            if(group1.getCheckedRadioButtonId()==R.id.updateRadioButton1)
              {
              clickitem1=“male”;
              Log.i(“VALUE OF clickitem1”,clickitem1);
             
              }
            if(group1.getCheckedRadioButtonId()==R.id.updateRadioButton2)
              {
              clickitem1=“female”;
              Log.i(“VALUE OF clickitem1”,clickitem1);
             
              }
           
            //validation
           
            if(clickitem1==”“)flag=true;
           
           
            else if(update_name.getText().toString() == null)
              {
              flag=true;
              Log.i(“VALUE OF FLAG1”,flag.toString());
              }
           
            else if(update_age.getText().toString().isEmpty())
            {
              flag=true;
              Log.i(“VALUE OF FLAG2”,flag.toString());
            }
            else if(spinner1.getSelectedItem().toString().isEmpty())
              {
                  flag=true;
                  Log.i(“VALUE OF FLAG3”,flag.toString());
              }
            else
            {
              flag = false;
           
            Log.i(“VALUE OF FLAG4”,flag.toString());
            }
           
            if(flag==true){
             
                  final AlertDialog alert_dlg1=new AlertDialog.Builder(Update1class.this).create();
                  alert_dlg1.setMessage(“Fill all the field”);
                 
                  alert_dlg1.setButton(“Ok”,new DialogInterface.OnClickListener(){
                 
                    public void onClick(DialogInterface dialog, int id){
                      alert_dlg1.cancel();
                   
                    }
                  });
                 
                  alert_dlg1.show(); 
                 
                 
                  }
            //confirmation dialog box
          if(flag == false){
             
           
              name_value1=update_name.getText().toString();
              age_value1 =Integer.parseInt(update_age.getText().toString());
              qualifications1=spinner1.getSelectedItem().toString();
             
              //dialog box
           
              AlertDialog dialog = new AlertDialog.Builder(Update1class.this).create();
                            dialog.setMessage(“Do you want to save”);
             
              dialog.setButton(“Yes”,new DialogInterface.OnClickListener(){
              public void onClick(DialogInterface dialog, int id)
              {
                    Log.i(“name:”, “”+name_value1);
                    Log.i(“age:”, “”+age_value1);
                    Log.i(“qualification:”, “”+qualifications1);
                    Log.i(“clickitem:”, “”+clickitem1);
                    //dbcls.updatedata(studentname, name_value1, age_value1, qualifications1,clickitem1);
                    dbcls.upDatePerson(studentname, name_value1, age_value1, qualifications1, clickitem1);
                   
              }
              });
              dialog.setButton2(“No”,new DialogInterface.OnClickListener(){
              public void onClick(DialogInterface dialog, int id)
              {
                 
              }
              });
              dialog.show();     
               
         
           
            }   
           
           
           
          }
      };
     
     
      public void onDestroy()
      {
          super.onDestroy();
          dbcls.closeDB();
         
      }
     

    }


    ///////////////////////////////////////////////////////
    package com.first;

    import java.util.ArrayList;

    import com.first.R.id;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.Spinner;

    public class Updateclass extends Activity{

      Button update_back_button,update_submit_button;
      Spinner spinner;
      DBclass dbu;
     
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.update);
         
          dbu=new DBclass(this);
          dbu.openDB();
          update_back_button=(Button)findViewById(R.id.updateback);
          update_submit_button=(Button)findViewById(R.id.updatesubmit);
         
          spinner=(Spinner)findViewById(R.id.updateSpinner1);
          ArrayList list=new ArrayList();
          list=dbu.getAllDetailsforupdate();
          spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,list));
          update_back_button.setOnClickListener(updateback);
          update_submit_button.setOnClickListener(updatesubmit);
         
      }
     
      OnClickListener   updateback =new OnClickListener() {
     
      @Override
      public void onClick(View v) {
          Intent intent=new Intent(Updateclass.this,Homeactivity.class);
          startActivity(intent);
         
      }
    };

      OnClickListener   updatesubmit=new OnClickListener() {
     
      @Override
      public void onClick(View v) {
          String stdName=spinner.getSelectedItem().toString();
          Intent intent=new Intent(Updateclass.this,Update1class.class);
          intent.putExtra(“Name”,stdName );
          startActivity(intent);
         
      }
    };
    }

  • pinky | 2:11 PM September 5, 2012

    package cb.webservice;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.PropertyInfo;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class WebService1Activity extends Activity
    {
     
      private final String NAMESPACE = “http://www.webserviceX.NET/”;
      private final String URL = “http://www.webservicex.net/ConvertWeight.asmx”;
      private final String SOAP_ACTION = “http://www.webserviceX.NET/ConvertWeight”;
      private final String METHOD_NAME = “ConvertWeight”;
     
      SoapPrimitive response ;
     
      EditText edit1;
      TextView text1;
      Button button1;
     
     
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
         
          edit1=(EditText)findViewById(R.id.editText1Value);
          text1=(TextView)findViewById(R.id.textView1Value);
         
          button1=(Button)findViewById(R.id.button1);
          button1.setOnClickListener(new View.OnClickListener()
          {
            public void onClick(View v)
            {         
              String kgValue = edit1.getText().toString();
              SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
             
              String weight = kgValue;
              String fromUnit = “Kilograms”;
              String toUnit = “Grams”;
             
              System.out.println(“Click”);
             
              PropertyInfo weightProp =new PropertyInfo();
              weightProp.setName(“Weight”);
              weightProp.setValue(weight);
              weightProp.setType(double.class);
              request.addProperty(weightProp);
               
              PropertyInfo fromProp =new PropertyInfo();
              fromProp.setName(“FromUnit”);
              fromProp.setValue(fromUnit);
              fromProp.setType(String.class);
              request.addProperty(fromProp);
               
              PropertyInfo toProp =new PropertyInfo();
              toProp.setName(“ToUnit”);
              toProp.setValue(toUnit);
              toProp.setType(String.class);
              request.addProperty(toProp);
             
              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
              envelope.dotNet = true;
              envelope.setOutputSoapObject(request);
              HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
         
              try
              {
                  System.out.println(“try”);
                  androidHttpTransport.call(SOAP_ACTION, envelope);
                  System.out.println(“first”);
                  response = (SoapPrimitive)envelope.getResponse();
                  System.out.println(“second”);
                  Log.i(“myApp”, response.toString());
           
                 
                text1.setText(response.toString()+ ” “+toUnit);
             
              }
              catch (Exception e)
              {
                  e.printStackTrace();
              }
              // text1.setText(response.toString()+ ” “+toUnit);
             
            }
          });     
         
         
      }
    }

  • pinky | 2:15 PM September 5, 2012

    package com.androidpeople.xml.parsing;

    import java.net.URL;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    public class XMLParsingDOMExample extends Activity {

      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
         
          LinearLayout layout = new LinearLayout(this);
          layout.setOrientation(1);
         
          TextView name[];
          TextView website[];
          TextView category[];

          try {

            URL url = new URL(
                  “http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml”);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName(“item”);

            /** Assign textview array lenght by arraylist size */
           
            name = new TextView[nodeList.getLength()];
            website = new TextView[nodeList.getLength()];
            category = new TextView[nodeList.getLength()];

            for (int i = 0; i < nodeList.getLength(); i++) {

              Node node = nodeList.item(i);
             
              name = new TextView(this);
              website = new TextView(this);
              category = new TextView(this);

              Element fstElmnt = (Element) node;
              NodeList nameList = fstElmnt.getElementsByTagName(“name”);
              Element nameElement = (Element) nameList.item(0);
              nameList = nameElement.getChildNodes();
              name.setText(“Name = “
                    + ((Node) nameList.item(0)).getNodeValue());

              NodeList websiteList = fstElmnt.getElementsByTagName(“website”);
              Element websiteElement = (Element) websiteList.item(0);
              websiteList = websiteElement.getChildNodes();
              website.setText(“Website = “
                    + ((Node) websiteList.item(0)).getNodeValue());

              category.setText(“Website Category = “
                    + websiteElement.getAttribute(“category”));

              layout.addView(name);
              layout.addView(website);
              layout.addView(category);

            }
          } catch (Exception e) {
            System.out.println(“XML Pasing Excpetion = ” + e);
          }

          /** Set the layout view to display */
          setContentView(layout);

      }
    }

  • pinky | 2:19 PM September 5, 2012

    package com.viju.sqlQuary;

    import java.util.ArrayList;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;

    public class Database extends SQLiteOpenHelper
    {
      //final static means single non changeable values
      private static final String DBname=“personDB2”;
      private static final int DBversion=1;
      //instance of SQLiteDatabase
      private SQLiteDatabase DB = null; 
      public Database(Context context) {       
          super(context, DBname, null, DBversion);
          Log.i(“1st call#constecter”, “Calling constector…”);
      } 
        public void openDB() throws SQLException {             
            if(this.DB == null)
            {         
              this.DB = this.getWritableDatabase();         
              //Create and/or open a database that will be used for reading and writing. The first time this is called,
              //the database will be opened and onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and/or
              //onOpen(SQLiteDatabase) will be called.

            }
          }     
        public void closeDB()
          {
            if(this.DB != null)
            {
              if(this.DB.isOpen())
                  this.DB.close();
            }
          }
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          //overriding from SQLiteOpenHelper
          //not that imp
          //db.execSQL(“DROP TABLE IF EXISTS Person”);
          //onCreate(db);       
      }
     
      //must
      @Override
      public void onCreate(SQLiteDatabase db) {
          //overriding from SQLiteOpenHelper    
          db.execSQL(“create table Person(name text,age integer);”);     
      }
      //###################################################
      //user define
        public void insert(String name,int age)
          {
            //DB.execSQL(“insert into Person values(’”+name+”’,’”+age+”’);”);
          DB.execSQL(“insert into Person values(’”+name+”’,”+age+”);”);
          }
     
        public void delete(String name)
          {
            DB.execSQL(“delete from Person where name=’”+name+”’;”);
          }
        public void update(String oldName,String newName,String NewAge)
          {
            DB.execSQL(“update Person set name=’”+newName+”’, age=’”+NewAge+”’ where name=’”+oldName+”’;”);
          }
       
        public ArrayList<String> getData()
          {       
            ArrayList result = new ArrayList();       
            Cursor cursor = this.DB.rawQuery(“select * from Person;”, null);
               
            if(cursor.getCount() >0)
            {       
              while (cursor.moveToNext())
              {
                  String name=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
                  String age= cursor.getString(cursor.getColumnIndex(“age”)) ;
                  //cursor.getColumnName(columnIndex)             
                  result.add(“Name : “+name+”  Age:”+age); 
                }                 
            }     
            return result;
          } 
    }

  • pinky | 9:02 PM September 5, 2012

    package com.login;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class LoginpageActivity extends Activity {
      /** Called when the activity is first created. */
      private EditText username;
      private EditText password;

      public String user_name;
      public String pass_word;

      DBclass db;
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          db=new DBclass(this);
          db.openDB();
         
          username = (EditText) findViewById(R.id.et_un);
          password = (EditText) findViewById(R.id.et_pw);

          final Button button = (Button) findViewById(R.id.btn_login);
          button.setOnClickListener(new View.OnClickListener() {       
            public void onClick(View v) {         

              user_name = username.getText().toString();
              pass_word = password.getText().toString();

             
             
              if (db.validateUser(user_name,pass_word)) {
                  Intent goToNextActivity = new Intent(getApplicationContext(),second.class);
                  startActivity(goToNextActivity);

              }
              else
                Toast.makeText(LoginpageActivity.this, “Wrong username/password”, Toast.LENGTH_LONG).show();

            }
             
           
          });
      }
         
    }


    package com.login;

    import java.util.ArrayList;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;

    public class DBclass extends SQLiteOpenHelper{
     
      private final static String DBname=“Mydatabase”;
      private final static int   DBversion=1;
      private final static String TABLE=“StudentInformation”;
      private final static String USERNAME=“name”;
      private final static String AGE=“age”;
      private static int age=0;
      private final static String PASSWORD=“qualification”;
      private final static String GENDER=“gender”;
      public static final String KEY_ROWID = “_id”;
      private final static String DB_script=“Create table “+TABLE+” (_id integer primary key autoincrement,”+USERNAME+” text not null,”+
      PASSWORD+” text not null);”;
       

       
      private SQLiteDatabase SQLdb = null;

      public DBclass(Context context) {
          super(context, DBname,null,DBversion);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {
          Log.i(“student information”, “Creating Table”);
          db.execSQL(DB_script);
         
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          // TODO Auto-generated method stub
         
      }
     
     
     
      public boolean openDB() throws SQLException
      {
       
          if(this.SQLdb == null)
          {
            Log.i(“creating”, “Creating sqliteDBInstance…”);
            this.SQLdb = this.getWritableDatabase();
            return true;
          }
          else
          return false;
      }
     
      public void closeDB()
      {
          if(this.SQLdb != null)
          {
            if(this.SQLdb.isOpen())
              this.SQLdb.close();
          }
      }
     
     

      public long Insertdata(String STD_name,String STD_quali )
      {
          ContentValues contentValues = new ContentValues();     
          contentValues.put(USERNAME, STD_name);
          //contentValues.put(“age”, STD_age);
          contentValues.put(PASSWORD, STD_quali);
          //contentValues.put(GENDER,STD_gender);
          Log.i(“Insert data==”, STD_name);
          return this.SQLdb.insert(TABLE, null, contentValues);
          //return this.SQLdb.insert(table, nullColumnHack, values)
         
      }
     
     
      public boolean validateUser(String username, String password){
            Cursor c = getReadableDatabase().rawQuery(
                  “SELECT * FROM ” + TABLE + ” WHERE “
                      + USERNAME + “=’” + username +“‘AND “+PASSWORD+”=’”+password+”’” ,  null);
            if (c.getCount()>0)
              return true;
              return false;
          }

     

     


    <?xml version=“1.0” encoding=“utf-8”?>

    <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
      android:layout_width=“fill_parent”
      android:layout_height=“fill_parent”
      android:layout_marginTop=“10dip”
      android:background=”#DDDDDD”>
      <TextView
          android:id=”@+id/tv_un”
          android:layout_width=“wrap_content”
          android:layout_height=“wrap_content”
          android:textSize=“10pt”
          android:textColor=”#444444”
          android:layout_alignParentLeft=“true”
          android:layout_marginRight=“9dip”
          android:layout_marginTop=“20dip”
          android:layout_marginLeft=“10dip”
          android:text=“User Name:”>
      <EditText
          android:id=”@+id/et_un”
          android:layout_width=“150dip”
          android:layout_height=“wrap_content”
          android:background=”@android:drawable/editbox_background”
          android:layout_toRightOf=”@id/tv_un”
          android:layout_alignTop=”@id/tv_un”>
        <TextView
          android:id=”@+id/tv_pw”
          android:layout_width=“wrap_content”
          android:layout_height=“wrap_content”
          android:textSize=“10pt”
          android:textColor=”#444444”
          android:layout_alignParentLeft=“true”
          android:layout_below=”@id/tv_un”
          android:layout_marginRight=“9dip”
          android:layout_marginTop=“15dip”
          android:layout_marginLeft=“10dip”
          android:text=“Password:”>
      <EditText
          android:id=”@+id/et_pw”
          android:layout_width=“150dip”
          android:layout_height=“wrap_content”
          android:background=”@android:drawable/editbox_background”
          android:layout_toRightOf=”@id/tv_pw”
          android:layout_alignTop=”@id/tv_pw”
          android:layout_below=”@id/et_un”
          android:layout_marginLeft=“17dip”
          android:password=“true”      >
      <Button
          android:id=”@+id/btn_login”
          android:layout_width=“100dip”
          android:layout_height=“wrap_content”
          android:layout_below=”@id/et_pw”
          android:layout_alignParentLeft=“true”
          android:layout_marginTop=“15dip”
          android:layout_marginLeft=“110dip”
          android:text=“Login” >
        <TextView
          android:id=”@+id/tv_error”
          android:layout_width=“fill_parent”
          android:layout_height=“40dip”
          android:textSize=“7pt”
          android:layout_alignParentLeft=“true”
          android:layout_below=”@id/btn_login”
          android:layout_marginRight=“9dip”
          android:layout_marginTop=“15dip”
          android:layout_marginLeft=“15dip”
          android:textColor=”#AA0000”
          android:text=”“>
    </RelativeLayout>

  • NAGESH | 5:15 AM November 16, 2013

    I want the parsing of xml containing the code of
    images and multiple tags
    like <roots>
        <root id=“1” img=”...jpg”>
        <types>
          <type name=”“>
          <file>
            <cont name=”“>
              <a>
              </a>
             
             

            </cont>
            </file>
          </type>
          <type….>
            ...
          </type>
        </types>
        <root…..
            ....
        </root>
      </roots>

Add your comment below

Remember me

Please enter the word you see in the image below:


*  Please be aware that all comments are moderated.

Interested in a particular topic?

If there are specific topics youd like to see us discuss on our blog or other ideas youd like to share, please let us know. Click here to contact us.