I am having some trouble parsing XML in Android from an URL. I don't know if it's the XML parsing that's the problem or only when I am trying to show it on the screen because
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this, android.R.layout.simple_list_item_1, stopNumbers));
wont show anything. The code below works perfectly in a java program.
URL: http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0
try {
ArrayList<Double> xCords = new ArrayList<Double>();
ArrayList<Double> yCords = new ArrayList<Double>();
ArrayList<String> stopNumbers = new ArrayList<String>();
ArrayList<String> bussLocations = new ArrayList<String>();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder
.parse(new URL(
"http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0")
.openStream());
// normalize text representation
doc.getDocumentElement().normalize();
NodeList listOfObjects = doc.getElementsByTagName("iGNMObject");
for (int s = 0; s < listOfObjects.getLength(); s++) {
Node firstPersonNode = listOfObjects.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList stopNumList = firstPersonElement
.getElementsByTagName("StopNumber");
Element ageElement = (Element) stopNumList.item(0);
if (ageElement != null) {
NodeList textAgeList = ageElement.getChildNodes();
String stop = ((Node) textAgeList.item(0))
.getNodeValue().trim();
stopNumbers.add(stop);
// ------
// -------
NodeList xPosList = firstPersonElement
.getElementsByTagName("XPosition");
Element firstNameElement = (Element) xPosList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
String temp2 = ((Node) textFNList.item(0))
.getNodeValue().trim();
double x = Double.parseDouble(temp2);
xCords.add(x);
// -------
NodeList yPosList = firstPersonElement
.getElementsByTagName("YPosition");
Element lastNameElement = (Element) yPosList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
String temp3 = ((Node) textLNList.item(0))
.getNodeValue().trim();
double y = Double.parseDouble(temp3);
yCords.add(y);
// ----
NodeList stopAkaList = firstPersonElement
.getElementsByTagName("StopAka");
Element stopAka = (Element) stopAkaList.item(0);
NodeList textStopAKAList = stopAka.getChildNodes();
String plats = ((Node) textStopAKAList.item(0))
.getNodeValue().trim();
bussLocations.add(plats);
} else {
}
}// end of if clause
}// end of for loop with s var
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this,
android.R.layout.simple_list_item_1, stopNumbers));
} catch (Exception e) {
}
}
}
}
Solved it. I had forgot to add internet permission in the manifest.
Related
Actually i try to do xml parsing from my local host and retrieve the value into the spinner.
what my doubt is i also need to retrieve the value inside the attribute which was present inside the book node (i,e) . I refer many tutorials and source codes still i cant able to do it. Any one please help to do it. Thanks in advance.
XML Structure
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>
An in-depth look at creating applications with XML.
</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>
A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.
</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>
After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.
</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>
In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.
</description>
</book>
</catalog>
Java code
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
ArrayList<String> title;
Button button;
Spinner spinner;
ArrayAdapter<String> from_adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = new ArrayList<String>();
button = (Button) findViewById(R.id.button1);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
parse();
from_adapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_item, title);
from_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(from_adapter);
}
});
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(), ""+spinner.getSelectedItem().toString().trim(),
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://10.0.2.2/book.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element idElmnt = (Element) node;
NodeList idList = idElmnt.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);
idList = idElement.getChildNodes();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("author");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("title");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("genre");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("price");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) idList.item(0)).getNodeValue()+":"+((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
try this code inside for loop.
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String value=node.getNodeValue();// you can store this in array for all nodes
Element idElmnt = (Element) node;
NodeList idList = idElmnt.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);
idList = idElement.getChildNodes();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("author");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("title");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("genre");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("price");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) idList.item(0)).getNodeValue()+":"+((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
I have an rss feed where, in every item tag there are two tags named category. I want to get the value of the first one,but unfortunately i get the second one value. This is my code:
// Create required instances
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
// to length einai posa nea tha emfanisei.Edw tou lew ola pou
// vriskei
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
if (thisNode != null && thisNode.getFirstChild() != null) {
theString = thisNode.getFirstChild().getNodeValue();
}
if (theString != null) {
String nodeName = thisNode.getNodeName();
...
....
...
if ("category".equals(nodeName)) {
/*
* NodeList nlList = nl.item(0).getChildNodes();
* Node nValue2 = (Node) nlList.item(0);
* _item.setCategory(nValue2.getNodeValue());
*/
_item.setCategory(theString);
}
}
}
EDIT:
My RSS feed is like:
<item>
<title>my title</title>
<category>Sports</category>
<category>World</category>
</item>
<item>
<title>my title 2</title>
<category>News</category>
<category>Showbiz</category>
</item>
...etc
if you want to get first category from current item Nodes then use Element.getElementsByTagName("category") for getting all category nodes in NodeList and after that use NodeList.item(0) to get first category Element from NodeList do it as:
Element element = (Element) currentNode;
NodeList nodelist = element.getElementsByTagName("category");
Element element1 = (Element) nodelist.item(0);
NodeList category = element1.getChildNodes();
System.out.print("category : " + (category.item(0)).getNodeValue());
Here is my code. I want to see these parsed strings into ListView in Android. How can I do this?
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(0);
System.out.println("Name: " + getCharacterDataFromElement(line));
NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
I am consuming a web service as its output is an XML string. I am parsing it into a document and getting each child node value one by one and inserting into my SQLlite table as shown below:
public void DownloadAndInsertProblemAndReasonCode(String serverIPAddress,
String deviceId) {
String SOAP_ACTION = "http://VisionEPODWebService/GetProblemAndReasonCodesNew";
String OPERATION_NAME = "GetProblemAndReasonCodesNew";
String WSDL_TARGET_NAMESPACE = "http://VisionEPODWebService/";
String SOAP_ADDRESS = "";
SOAP_ADDRESS = "http://" + serverIPAddress
+ "/VisionEPODWebService/SystemData.asmx";
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
request.addProperty("deviceID", deviceId);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
DocumentBuilderFactory docBuilberFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilberFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource
.setCharacterStream(new StringReader(response.toString()));
Document doc = docBuilder.parse(inputSource);
NodeList nodesProblemCode = doc
.getElementsByTagName("tblProblemCode");
ContentValues initialProblemCodeValues = new ContentValues();
dbAdapter = new DatabaseAdapter(this.context);
dbAdapter.open();
dbAdapter.BeginTransaction();
dbAdapter.DeleteRecord("tblProblemCode", "", "");
for (int i = 0; i < nodesProblemCode.getLength(); i++) {
Element element = (Element) nodesProblemCode.item(i);
NodeList PKProblemCode = element
.getElementsByTagName("PKProblemCode");
Element line = (Element) PKProblemCode.item(0);
initialProblemCodeValues.put("PKProblemCode",
getCharacterDataFromElement(line).toString());
NodeList ProblemCode = element
.getElementsByTagName("ProblemCode");
line = (Element) ProblemCode.item(0);
initialProblemCodeValues.put("ProblemCode",
getCharacterDataFromElement(line));
NodeList ProblemCodeDescription = element
.getElementsByTagName("ProblemCodeDescription");
line = (Element) ProblemCodeDescription.item(0);
initialProblemCodeValues.put("ProblemCodeDescription",
getCharacterDataFromElement(line).toString());
NodeList VWReturn = element.getElementsByTagName("VWReturn");
line = (Element) VWReturn.item(0);
initialProblemCodeValues.put("VWReturn",
getCharacterDataFromElement(line).toString());
dbAdapter.InsertRecord("tblProblemCode", "",
initialProblemCodeValues);
}
NodeList nodesReasonCode = doc
.getElementsByTagName("tblReasonCode");
ContentValues initialReasonCodeValues = new ContentValues();
dbAdapter.DeleteRecord("tblReasonCode", "", "");
for (int i = 0; i < nodesReasonCode.getLength(); i++) {
Element element = (Element) nodesReasonCode.item(i);
NodeList PKReasonCode = element
.getElementsByTagName("PKReasonCode");
Element line = (Element) PKReasonCode.item(0);
initialReasonCodeValues.put("PKReasonCode",
getCharacterDataFromElement(line).toString());
NodeList ReasonDescription = element
.getElementsByTagName("ReasonDescription");
line = (Element) ReasonDescription.item(0);
initialReasonCodeValues.put("ReasonDescription",
getCharacterDataFromElement(line));
dbAdapter.InsertRecord("tblReasonCode", "",
initialReasonCodeValues);
}
dbAdapter.SetSucessfulTransaction();
dbAdapter.EndTransaction();
dbAdapter.close();
}
catch (Exception exception) {
exception.toString();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
The problem is that after some time the XML string will not have some of child node. For example
"ProblemCode" child node.....at that time the code shows error.
How can I check whether there exists an element in the document, or whether values exist or not for the element?
I think you need to check if the child node exists: specifically for your problem node:
NodeList NL = element.getElementsByTagName("PKProblemCode");
if ((NL==null)||(NL.getLength()==0)) {
//No such node so use a default instead
} else
Element line = (Element) PKProblemCode.item(0);
i have parsed xml using dom parser,but when the xml element contains no value it throws null pointer Exception.how to check this?...
here my code
NodeList TrackName1 = fstElmnt2.getElementsByTagName("Artist_Name");
Element TrackElement1 = (Element) TrackName1.item(0);
TrackName1 = TrackElement1.getChildNodes();
result=result+((Node) TrackName1.item(0)).getNodeValue()
String Artistname=((Node)TrackName1.item(0)).getNodeValue();
}
Just check for null before you try to use the value?
Object value = ((Node) TrackName1.item(0)).getNodeValue();
if (value != null) {
result = result + value;
}
NodeList nodeList = doc.getElementsByTagName("item");
description = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
description[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList dataList = fstElmnt.getElementsByTagName("description");
Element dataElement = (Element) dataList.item(0);
dataList = dataElement.getChildNodes();
description[i].setText( ((Node) dataList.item(0)).getNodeValue());