title: Parsing XML in Android with SAX
body: <p>I have an XML file, like so:</p>
  
  <pre><code>&lt;questions title="(Some question Category)"&gt;
   &lt;question&gt;
    &lt;ask&gt;(Some question)?&lt;/ask&gt;
    &lt;answer&gt;(Some answer)&lt;/answer&gt;
    &lt;answer correct="true"&gt;(Some correct answer)&lt;/answer&gt;
    &lt;answer&gt;(Some answer)&lt;/answer&gt;
    &lt;answer&gt;(Some answer)&lt;/answer&gt;
   &lt;/question&gt;
  &lt;/questions&gt;
  </code></pre>
  
  <p>And I am using SAX to parse the file. As far as I know, all of the required SAX files are set up correctly.</p>
  
  <p>I then have a handler class that I looked up how to code for a slightly different XML file. I tried adjusting it for the xml above and here's what I came up with (not finished):</p>
  
  <pre><code>import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.net.URL;
  import java.net.URLConnection;
  import java.util.ArrayList;
  import javax.xml.parsers.SAXParser;
  import javax.xml.parsers.SAXParserFactory;
  import org.xml.sax.Attributes;
  import org.xml.sax.InputSource;
  import org.xml.sax.SAXException;
  import org.xml.sax.XMLReader;
  import org.xml.sax.helpers.DefaultHandler;
  import android.content.Context;
  import android.graphics.Color;
  import android.util.Log;
  import android.widget.TextView;
  
  public class QuestionHandler extends DefaultHandler {
      //list for imported product data
      private ArrayList&lt;TextView&gt; theViews;
      //string to track each entry
      private String currQuestion = "";
      //flags to keep track of XML processing
      private boolean isAsk = false;
      private boolean isAnswer = false;
      //context for user interface
      private Context theContext;
      //constructor
      public QuestionHandler(Context cont) {
          super();
          theViews = new ArrayList&lt;TextView&gt;();
          theContext = cont;
      }
  
      //start of the XML document
      public void startDocument () { Log.i("QuestionHandler", "Start of XML document"); }
  
      //end of the XML document
      public void endDocument () { Log.i("QuestionHandler", "End of XML document"); }
  
      //opening element tag
      public void startElement (String uri, String name, String qName, Attributes atts)
      {
          //find out if the element is a question
          if(qName.equals("question"))
          {
              //set ask and answer tag to false
              isAsk = false;
              isAnswer = false;
              //create View item for question display
              TextView questionView = new TextView(theContext);
              questionView.setTextColor(Color.rgb(73, 136, 83));
              //add the attribute value to the displayed text
              String viewText = "Items from " + atts.getValue("name") + ":";
              questionView.setText(viewText);
              //add the new view to the list
              theViews.add(questionView);
          }
          //or if the element is an asked question
          else if(qName.equals("ask"))
              isAsk = true;
  
          //or if element is an answer
          else if(qName.equals("answer"))
              isAnswer = true;
      }
  
      //closing element tag
      public void endElement (String uri, String name, String qName)
      {
          if(qName.equals("question"))
          {
              //create a View item for the asked
              TextView askView = new TextView(theContext);
              askView.setTextColor(Color.rgb(192, 199, 95));
              //display the compiled items
              askView.setText(currQuestion);
              //add to the list
              theViews.add(askView);
              //create a View item for the answers
              TextView answersView = new TextView(theContext);
              answersView.setTextColor(Color.rgb(192, 199, 95));
              //display the compiled items
              answersView.setText(currQuestion);
              //add to the list
              theViews.add(answersView);
              //reset the variable for future items
              currQuestion = "";
          }
      }
  
      //element content
      public void characters (char ch[], int start, int length)
      {
          //string to store the character content
          String currText = "";
          //loop through the character array
          for (int i=start; i&lt;start+length; i++)
          {
              switch (ch[i]) {
              case '\\':
                  break;
              case '"':
                  break;
              case '\n':
                  break;
              case '\r':
                  break;
              case '\t':
                  break;
              default:
                  currText += ch[i];
                  break;
              }
          }
          //prepare for the next item
          if(isAsk || isAnswer &amp;&amp; currText.length()&gt;0)
              currQuestion += currText+"\n";
      }
      public ArrayList&lt;TextView&gt; getData()
      {
          //take care of SAX, input and parsing errors
          try
          {
              //set the parsing driver
              System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
              //create a parser
              SAXParserFactory parseFactory = SAXParserFactory.newInstance();
              SAXParser xmlParser = parseFactory.newSAXParser();
              //get an XML reader
              XMLReader xmlIn = xmlParser.getXMLReader();
              //instruct the app to use this object as the handler
              xmlIn.setContentHandler(this);
              //provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
              URL xmlURL = new URL("http://www.macs.hw.ac.uk/~pjbk/quiz/example.xml");
              //open the connection and get an input stream
              URLConnection xmlConn = xmlURL.openConnection();
              InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
              //build a buffered reader
              BufferedReader xmlBuff = new BufferedReader(xmlStream);
              //parse the data
              xmlIn.parse(new InputSource(xmlBuff));
          }
          catch(SAXException se) { Log.e("AndroidTestsActivity", 
                  "SAX Error " + se.getMessage()); }
          catch(IOException ie) { Log.e("AndroidTestsActivity", 
                  "Input Error " + ie.getMessage()); }
          catch(Exception oe) { Log.e("AndroidTestsActivity", 
                  "Unspecified Error " + oe.getMessage()); }
          //return the parsed product list
          return theViews;
      }
  
  }
  </code></pre>
  
  <p>Finally, my initialiseQuestions() method, from an otherwise working activity, is what allocates the extracted XML data to a question class(again, unfinished):</p>
  
  <pre><code>private void initialiseQuestions() {
      // TODO Auto-generated method stub
  
      questions = new Vector&lt;Question&gt;(); //Vector containing our questions
  
      try
      {
          //create an instance of the QuestionHandler class
          QuestionHandler handler = new QuestionHandler(getApplicationContext());
          //get the string list by calling the public method
          ArrayList&lt;TextView&gt; newViews = handler.getData();
          //convert to an array
          Object[] question = newViews.toArray();
          //loop through the items, creating a View item for each
          for(int i=0; i&lt;question.length; i++)
          {
              //add the next question in the list
              Question q1 = new Question(question[i]);
              q1.addAnswer("Harold Godwin", false);
              q1.addAnswer("Edward the Confessor", false);
              q1.addAnswer("William the Conqueror", true);
              q1.addAnswer("Alfred the Great", false);
              questions.add(q1);
              //mainLayout.addView((TextView)products[i]);
          }
  
      }
      catch(Exception pce) { Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); }
  </code></pre>
  
  <p>My main issue is I do not really understand what I am doing/need to change in the handler and the initialiseQuestions method. I don't get how the string is created in the handler (why are textViews needed if you just need a string array sent back?) and I don't understand how to process the data back in initialiseQuestions. As you can see the initaliseQuestions method should take the parsed XML and instantiate a question object with the data.</p>
  
  <p>Could someone tell me what I need to change?</p>
  
  <p><a href="http://www.codeproject.com/Articles/334859/Parsing-XML-in-Android-with-SAX" rel="nofollow">Here's the tutorial</a> I've been trying to adjust </p>