I'm trying to parse the XML HttpResponse i get from a HttpPost to a server (last.fm), for a last.fm android app. If i simply parse it to string i can see it being a normal xml string, with all the desired information. But i just cant parse the single NameValuePairs. This is my HttpResponse object:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
I tried two different things and non of them worked. First i tried to retrieve the NameValuePairs:
List<NameValuePair> answer = URLEncodedUtils.parse(r_entity);
String name = "empty";
String playcount = "empty";
for (int i = 0; i < answer.size(); i++){
if (answer.get(i).getName().equals("name")){
name = answer.get(i).getValue();
} else if (answer.get(i).getName().equals("playcount")){
playcount = answer.get(i).getValue();
}
}
After this code, name and playcount remain "empty". So i tried to use a XML Parser:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document answer = db.parse(new DataInputStream(r_entity.getContent()));
NodeList nl = answer.getElementsByTagName("playcount");
String playcount = "empty";
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
Node fc = n.getFirstChild();
playcount Url = fc.getNodeValue();
}
This seems to fail much earlier since it doesn't even get to setting the playcount variable. But like i said if i perform this:
EntityUtils.toString(r_entity);
I will get a perfect xml string. So it should no problem to pars it since the HttpResponse contains the correct information. What am i doing wrong?
You can't use == to compare a String
When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.
Here's the correct way to compare two strings.
Taken from Top Ten Errors Java Programmers Make
I solved it. The DOM XML parser needed a little more adjustment:
This is a very good tutorial on parsing XML from a feed. You can use it to build more robust apps that need to parse XML feeds I hope it helps