Filip Vuković Filip Vuković - 25 days ago 17
Java Question

How to store xml in list in Android studio

TextView Naziv[];
TextView Id[];
int a = 0;

//ovaj primjer sam nasao na netu, treba parsirat XML
//ali nisam siguran da li treba podatke parsirat u ovoj klasi ili u nekoj drugoj
//probaj to skuzit


try{
String address = "http://www.dajsve.com/rss.ashx?svigradovi=1";
URL gradoviXmlUrl = new URL(address);

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(gradoviXmlUrl.openStream());

doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("Grad");

Naziv = new TextView[nodeList.getLength()];

List<Grad> gradoviLista = null;

for(int i=0; i<nodeList.getLength(); i++){
Element element = (Element) nodeList.item(i);
NodeList nazivGrada = element.getElementsByTagName("Naziv");
NodeList idGrada = element.getElementsByTagName("Id");
Element nazivGradaElement = (Element) nazivGrada.item(i);
Element idGradaElement = (Element) idGrada.item(i);
String gradNaziv = nazivGradaElement.getAttribute("Naziv");


/*Grad grad = null;
grad.setNaziv(nazivGrada);
grad.setId(idGradaElement);


gradoviLista.add(idGradaElement, nazivGradaElement);*/

}

a = nodeList.getLength();
//ovdje u varijablu zapisujem broj gradova, koje kasnije koristim samo za provjeru u main aktivitiju


The fetch from web service works, in variable a i store the length of elements, but the storing into variables does'nt work.

Element element = (Element) nodeList.item(i);
NodeList nazivGrada = element.getElementsByTagName("Naziv");
NodeList idGrada = element.getElementsByTagName("Id");
Element nazivGradaElement = (Element) nazivGrada.item(i);
Element idGradaElement = (Element) idGrada.item(i);
String gradNaziv = nazivGradaElement.getAttribute("Naziv");


This code does'nt work.

this is the xml: http://www.dajsve.com/rss.ashx?svigradovi=1
Can somebody help me?

Answer

nodeList.item(i); returns the node at the indexth position in the NodeList, a Node is not always an element so you will get a ClassCastException on:

Element element = (Element) nodeList.item(i);

Just make sure to check if(FPN.getNodeType() == Node.ELEMENT_NODE) before casting a Node to an Element

Or you can use:

Node node = nodeList.item(i);
            String gradNaziv  = getNodeValueByTagName(node ,"Naziv");
Comments