Dom parsing in Android - 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.

Related

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.

Easy way to get the node value of this example

I have a sample XML (Android platform) and I wanted to know the easiest and most efficient approach to get the node value of the node "e". Please help.
<a>
<b>
<c>
<e>data</e>
</c>
</b>
<b>
</b>
</a>
Use XPath.
See - http://developer.android.com/reference/javax/xml/xpath/package-summary.html
The XPath expression to grab the correct element would be:
/a/b/c/e
You could coalesce the resulting node into a String to get the textual value.
I think following code will help you to extract data of "e" node.
NodeList nodes = doc.getElementsByTagName("b");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList nodesimg = element.getElementsByTagName("e");
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 "?";
}
Implement Pull Parser, example is given here: http://icodesnip.com/snippet/java/android-pull-parser-sample
So by your case, you have to write the condition inside the start tag for "e".

how to display xml parse value in spinner using 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..

Android Array String

Hi guys if i try to assign the string to string Array i am getting NULL POINTER EXCEPTION..
Pls give me a solution..
Here is my code and i am getting null pointer in this line thumbs[j]=title;
as code Follows...
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("title")) {
try{
property.normalize();
Spanned title2 = Html.fromHtml(property.getFirstChild().getNodeValue().replaceAll("\\<.*?>", ""));
title = title2.toString();
}catch(Exception e){
Log.v("Exception",""+e);
}
thumbs[j]=title;
}
}
}
My guess is that the thumbs[] hasn't been initialized doing something like:
String [] thumbs = new String [properties.getLength()];
Though it's hard to say - your code doesn't show your declaration of this array.
The only possibility is that thumbs is null. It isn't a compile error if you don't initialize it. Don't rely on the IDE to tell you if something initialized prove it to yourself by examining your code, or print out the value of thumbs before you use it every time.
The only other exception possibilities at that line are ArrayIndexOutOfBoundsException if j > thumbs.length-1. But again, that's not a NPE. If title was null, that's fine and not an exception.

Categories

Resources