how to display xml parse value in spinner using android? - android

I am developing an android application,I want to parse two node from url like,
chennai
12
i want to parse city name and corresponding id and display in spinner,when i choose particular city in spinner,display corresponding id in alert box,How will do,please guide me
Thanks

If you are xml is like this,
<channel>
<link>
<title> Test Values</title>
<item>
<cityid>
12</cityid>
<cityname>
chennai
</cityname>
</item>
</link>
</channel>
then parse these tokens using DOM or SAX and store it in an Array like this
For Instance, If you want to use DOM Parser, then refer this code
Step 1: Create a Method to parse City Id and create an array to store that parsed value
String[] cityid=null;
public void parse_id() throws UnknownHostException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
org.w3c.dom.Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("item);
int a=items.getLength();
int k=0;
bstagid=new String[a];
for (int i = 0; i < items.getLength(); i++) {
Message_category message = new Message_category();
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase(cityid)) {
message.setId(property.getFirstChild()
.getNodeValue());
cityid[k]=property.getFirstChild().getNodeValue();
k++;
}
}
}
} catch (Exception e) { }
}
Similarly for city name,
then in spinner, use ArrayAdapter, if chennai is showed then refer it as cityname array n's elemnt , then you can refer cityid array's n th elemnt, map the city id with city name, like this..

Related

parse XML file to get <img> tag "src" attributes value

I am trying to build a app that display the feed of a given twitter account without using Twitter's Oauth, instead I converted the twitter account feed page to an xml format using Twitrss.me the image src is buried inside the img tag under the src attribute
<img xmlns="http://www.w3.org/1999/xhtml" width="250"
src="https://pbs.twimg.com/media/CmEqtEuUoAISIC3.jpg"
xml:base="http://twitrss.me/twitter_user_to_rss/?user=capcomfighters" />
I was able to get all the other tags text content but I have no idea how to access the tag attributes and get the value for specific attribute
also if there is a better way to do this than parsing xml please let me know
I am using this function to get the content of the tags
private void ProcessXml(Document data) {
if (data != null) {
feedItems=new ArrayList<>();
Element root = data.getDocumentElement();
Node channel = root.getChildNodes().item(1);
NodeList items = channel.getChildNodes();
for (int i = 0; i < items.getLength(); i++) {
Node currentchild = items.item(i);
if (currentchild.getNodeName().equalsIgnoreCase("item")) {
FeedItem item=new FeedItem();
NodeList itemchilds = currentchild.getChildNodes();
for (int j = 0; j < itemchilds.getLength(); j++) {
Node current = itemchilds.item(j);
if (current.getNodeName().equalsIgnoreCase("title")){
item.setTitle(current.getTextContent());
item.setDescription(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("description")){
// item.setDescription(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("pubDate")){
item.setPubDate(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("img")){
item.setThumbnailUrl(current.getAttributes().getNamedItem("src").getNodeValue());
Log.d("PIC", "ProcessXml: "+current.getAttributes().getNamedItem("src").getNodeValue());
}
}
feedItems.add(item);
}
}
}
}

Parse XML data from url using DOM Parser

I want to parse xml file from url :
http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=cher&api_key=5d6ce941674603e4bb75cfad6cfa13b7
I want to parse following tags of the file :
<artist>
<name>Cher</name>
<image size="medium">http://userserve-ak.last.fm/serve/64/62286415.png</image>
</artist>
But i don't know how to get the value of these two tags only.
I have tried the example code from
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
But it does not showing to parse same tag having different attribute value.
Can anyone guide me how this is done?
Thanx in advance.
from the link you provided, I have just extract a small part :
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("artist");
// looping through all item nodes <artist>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
String name = parser.getValue(e, "name"));
String image = parser.getValue(e, "image"));
//if you want the artist 'Cher' sigh ;)
if (name.equals("Cher")){
//do whatever you want
}
}
Thankx. I solved my problem from this url :
Getting element using attribute
if(str.equals("image"))
{
n = item.getElementsByTagName(str);
for (int i = 0; i < n.getLength(); i++) {
Node subNode = n.item(i);
if (subNode.hasAttributes()) {
NamedNodeMap nnm = subNode.getAttributes();
for (int j = 0; j < nnm.getLength(); j++) {
Node attrNode = nnm.item(j);
if (attrNode.getNodeType() == Node.ATTRIBUTE_NODE) {
Attr attribute = (Attr) attrNode;
if( attribute.getValue().equals("medium"))
{
return this.getElementValue(n.item(i));
}
}
}
}
}
}

I need to parse the XML file in my android application. I dont know how many nodes it got

My activity class look like this:
AssetManager assetmgr= getAssets();
String list[] = assetmgr.list("subdir");
if (list != null) {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("subdir/fullSurvey.xml"));
xml object class looks like this:
NodeList root = doc.getElementsByTagName("root");
NodeList nlQuestions = root.item(0).getChildNodes();
QuestionObject[] allQuestions = new QuestionObject[nlQuestions.getLength()];
for (int i = 0; i < nlQuestions.getLength(); i++) {
Node question = nlQuestions.item(i);
NodeList childNodes = question.getChildNodes();
QuestionObject x = new QuestionObject();
for (int j = 0; j < childNodes.getLength(); j++) {
Node child = childNodes.item(j);
if (child.getNodeName() !="#text") {
Questions t = Questions.valueOf(child.getNodeName());
// etc.
I dont know how to parse xml file according to attribute value
I don't know that many XML parsers will traverse according to attribute values. Most deal with nodes, nodelists, etc. You may have to read in all the nodes and hash by the attribute values yourself.

Problem in parsing nested tags in xml

I have an xml that i am parsing through DOM parser. the xml is of somewhat this sequence
<root>
<item1> abc </item1>
<item2> def </item2>
<item3> ghi </item3>
<item4>
<subItem4>
<name> xyz </name>
<id> 1 </id>
</subItem4>
<subItem4>
<name> asd </name>
<id> 2 </id>
</subItem4>
</item4>
</root>
According to this dummy xml i am reaching till subItem 4 but not to the childern of it. what i am trying is as follows to get innermost Items is:
NodeList slide = theElement.getElementsByTagName("item4").item(0).getChildNodes();
for(int i = 0; i<slide.getLength(); i++)
{
NodeList subSlides = theElement.getElementsByTagName("subItem4").item(0).getChildNodes();
for (int j=0; j<subSlides.getLength(); j++)
{
String subSlide_title = subSlides.item(i).getFirstChild().getNodeValue();
}
}
its not working. please can someone identify where am i doing the mistake in parsing. Any help is appreciated.
You are not using valid XML - you can't have spaces in tag names.
XML Names cannot contain white space, see here for valid values.
Update (following comment that the posted sample is representative of the actual XML):
Your access via the indexer of the node list is incorrect:
String subSlide_title = subSlides.item(i).getFirstChild().getNodeValue();
Try this instead (using j instead of i, as the inner loop variable is called):
String subSlide_title = subSlides.item(j).getFirstChild().getNodeValue();
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList nodesimg = element.getElementsByTagName("name");
for (int j = 0; j < nodesimg.getLength(); j++) {
Element line = (Element) nodesimg.item(j);
String value=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 think above code will help you in parsing xml file.
The XML elements are all messed up.
There are literally 2 lines that don't have mistakes in them.
For instance
<subItem 4>
is syntactically wrong and I don't see what logical sense you could make out of it.
Do you mean
<subItem4>
as in the fourth sub item or
<subItem someAttribute="4">
I'd recommend learning XML, it's very simple... http://www.w3schools.com/xml/default.asp

Dom parsing in Android

If I parse the tag that contains <p>Some Text</p> tag, I get a null pointer exception.
My RSS feed is as follows:
<quaddeals_conditions><p>Limit one QuadDeal</p></quaddeals_conditions>
My code is:
if (name.equalsIgnoreCase("quaddeals_conditions")) {
property.normalize();
conditions = property.getFirstChild().getNodeValue();
}
You have an element inside an element .
Therefore retrieve all quaddeals and then iterate each one and retrieve from it the p element:
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.inputStream);
Element root = dom.getDocumentElement();
// snip
NodeList items = root.getElementsByTagName("quaddeals_conditions");
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("p")) {
property.getFirstChild().getNodeValue(); // Your paragraph data
}
}
}
Hope this helps.
is "name" not NULL? I dont see you check for that.
It's good coding practice to compare the other way if possible:
if ("quaddeals_conditions".equalsIgnoreCase(name))...
So even if "name" is NULL, you don't get a NullPointerException.
Always check for not null before accessing some object member.

Categories

Resources