Search code examples
androidxmlparsingxmlresourceparser

How do I parse and display things from an XML in an Android application?


The XML file I want to parse is

<?xml version="1.0" encoding="utf-8"?>
<items>
    <item>
        <question>Question?</question>
        <answer1>Answer 1 is fun</answer1>
        <answer2>Answer 2 is too</answer2>
        <answer3>Answer 3 is me</answer3>
        <answer4>Answer 4 no more</answer4>
        <correctanswer>Answer 1 is fun</correctanswer>
        <comment>Sent in by: Salamader Jack, I need help :(</comment>
    </item>
</items>

The code I have written so far may or may not be completely off. This is my first time writing a parser like this. I've been told there are many ways so please if there are other suggestions, feel free to let me know! :)

package assinment1.sfapps.com.myapplication;

import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;


class question {
    public String question;
    public String answer1;
    public String answer2;
    public String answer3;
    public String answer4;
    public String comment;
    public String correctAnswer;

}

public class TriviaGame extends Activity {
    ArrayList<question> questions;
    question q;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trivia_game);

        TextView myXmlContent = (TextView)findViewById(R.id.tvfun);
        String stringXmlContent;
        try {
            stringXmlContent = getEventsFromAnXML(this);
            myXmlContent.setText(stringXmlContent);
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private String getEventsFromAnXML(Activity activity)
            throws XmlPullParserException, IOException
    {
        //StringBuffer stringBuffer = new StringBuffer();
        Resources res = activity.getResources();
        XmlResourceParser xpp = res.getXml(R.xml.questions_q);
        xpp.next();
        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT)
        {
            q = new question();
            if(eventType == XmlPullParser.START_DOCUMENT || (xpp.getName() == "items" || xpp.getName() == "item" ))
            {
              //  stringBuffer.append("--- Start XML ---");
            }
            else if(eventType == XmlPullParser.START_TAG)
            {
                if(){

                }
                if(xpp.getName() == "question"){
                    q.question = xpp.getText();
                }else if(xpp.getName() ==  "answer1"){
                    q.answer1 = xpp.getText();
                }else if(xpp.getName() ==  "answer2"){
                    q.answer2 = xpp.getText();
                }else if(xpp.getName() ==  "answer3"){
                    q.answer3 = xpp.getText();
                }else if(xpp.getName() ==  "answer4"){
                    q.answer4 = xpp.getText();
                }else if(xpp.getName() ==  "comment"){
                    q.comment = xpp.getText();
                }else if(xpp.getName() ==  "correctAnswer"){
                    q.correctAnswer = xpp.getText();
                }
                questions.add(q);
               // stringBuffer.append("\nSTART_TAG: "+xpp.getName());
            }
            eventType = xpp.next();

        }

        return q.toString();
    }

    private void printQ(ArrayList<question> questions) {
        //findViewById()
    }


    @Override
public boolean onOptionsItemSelected(MenuItem item){
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id=item.getItemId();

        //noinspection SimplifiableIfStatement
        if(id==R.id.action_settings){
        return true;
        }

        return super.onOptionsItemSelected(item);
        }
}

Any help would be amazing. I do know that this code is unfinished.. It also crashes. I am trying to store the questions I take out of the XML in the array list I created. I am also trying to make sure this will store multiple questions. Thank you very much for even looking at this haha.


Solution

  • MyQs is a global array in my case.
    How to get the questions from the XML (this case stored in array).. if you need a none allocated try an ArrayList.

     public void getQuestionsfromXML() throws XmlPullParserException,
                IOException {
            String tagname = " ";
            XmlResourceParser xpp = getResources().getXml(R.xml.trivia);
    
            if (xpp == null) {
    
            } else {
                xpp.next();
                int eventType = xpp.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {
                        tagname = xpp.getName();
                    } else if (eventType == XmlPullParser.TEXT) {
                        setNextQuestion(tagname, xpp.getText());
    
                    }
                    eventType = xpp.next();
    
                }
            }
        }
    
     public void setNextQuestion(String tagname, String textin) {
    
            if (tagname.equals("question")) {
                myQs[myQsindex] = new myQuestion();
                myQs[myQsindex].Question = textin;
    
            }
            if (tagname.equals("answer1")) {
                myQs[myQsindex].Answer1 = textin;
    
            }
            if (tagname.equals("answer2")) {
                myQs[myQsindex].Answer2 = textin;
    
            }
            if (tagname.equals("answer3")) {
                myQs[myQsindex].Answer3 = textin;
    
            }
            if (tagname.equals("answer4")) {
                myQs[myQsindex].Answer4 = textin;
    
            }
            if (tagname.equals("correctanswer")) {
                myQs[myQsindex].correctAnswer = textin;
    
            }
    
            if (tagname.equals("comment")) {
                myQs[myQsindex].comment = textin;
                msg = "question-> " + myQs[myQsindex].Question + "\n" + "Answer:     " + myQs[myQsindex].correctAnswer + "Index: " + myQsindex;
    
                if (TotalNumberofQs < maxQs)// precaution here
                {
                    myQsindex++;
                    TotalNumberofQs++;
                }
            }
    

    Displaying it is obviously much more code but the basic idea is
    take the following code and use it to update the question whenever needed.

        private void displayQuestion() {
                //Text View
                question.setText(myQs[myQsindex].Question);
    
                //Text View Radio buttons
                Answer1.setText(myQs[myQsindex].Answer1);
                Answer2.setText(myQs[myQsindex].Answer2);
                Answer3.setText(myQs[myQsindex].Answer3);
                Answer4.setText(myQs[myQsindex].Answer4);
                correctAnswer = myQs[myQsindex].correctAnswer;
        }