Parsing a XML HttpResponse - android

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?

I solved it. The DOM XML parser needed a little more adjustment:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(inStream);
String playcount = "empty";
NodeList nl = doc.getElementsByTagName("playcount");
for(int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
playcount = nameElement.getFirstChild().getNodeValue().trim();
}
}

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

if (answer.get(i).getName() == "name"){
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.
String abc = "abc"; String def = "def";
// Bad way
if ( (abc + def) == "abcdef" )
{
......
}
// Good way
if ( (abc + def).equals("abcdef") )
{
.....
}
Taken from Top Ten Errors Java Programmers Make

Related

Parse multiple values and store [ANDROID]

I would like to parse a webservice response in xml on my android.
The way most "easy" what I did was this:
public String valor;
public static FormasDePagamento[] parseXML(String xml)
throws ParserConfigurationException, SAXException, IOException {
InputSource is = new InputSource(new StringReader(xml));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
FormasDePagamento[] formas = new FormasDePagamento[7];
for (int i = 0; i < 7; i++) {
formas[i] = new FormasDePagamento();
formas[i].valor = doc.getElementsByTagName("VALOR").item(i)
.getTextContent();
}
But now what I need is to get all that are in the result (which can be 7, but can also be 500 results) and in addition, each store a list to be displayed as a list in activity.
How can I develop this? Thank U!
You can pass your obtained list to an ArrayAdapter and show it on a ListView
ArrayAdapter<FormaDePagamento> adapter = new ArrayAdapter<FormaDePagamento>(context,android.R.layout_simple_list_item_1,parseXML(xml));
yourListView.setAdapter(adapter);
ArrayAdapter gets the toString() of your class, so remember to override it to show whatever info you want

Parsing check-in XML from google places api

I am trying to fetch checkin locations from Google places API but I am getting error for XML FileNotFoundException when I try to read it through url.openStream(). My key is correct because I tried using it in some other URL in browser. If someone has used this feature then please let me know how to do this. Here is my code:
public String checkingMessage()
{
String strURL = "https://maps.googleapis.com/maps/api/place/check-in/xml?sensor=true&key=" + GOOGLE_API_KEY;
URL url;
try
{
url = new URL(strURL.replace(" ", "%20"));
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(url.openStream()));
// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// Create a XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
expr = xpath.compile("//reference/text()");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
String answer = nodes.item(0).getNodeValue();
Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG);
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
If I use direct url in browser, I get following error:
400: Your client has issued a malformed or illegal request. That’s all we know.
I dont know json parsing, so I am using XML. Output I believe should be like this, hence I am trying to fetch value of reference:
<CheckInRequest>
<reference>place_reference</reference>
</CheckInRequest>
Update : I tried using HttpResponse and get response into Entity as follows
if (httpResponse.getStatusLine().getStatusCode() == 200){
strResult = EntityUtils.toString(httpResponse.getEntity());
}
But then I get MalFormedException on
doc = builder.parse(strResult); // doc is Document type
Either ways how can I get xml result into doc
I think you are trying to fetch check-in locations. I would like to do the same. But the check-in API seems to be POST-only at the moment, at least that's how I read the API documentation. Meaning your application can check-in, but you cannot query who checked in where (not even you yourself).

How to get sessionId from server if the login is authenticated in android?

I'm validating the form data as the response I'm getting total feed of that URL but i need only session Id from that how can i do this.can any body help regarding this..
Now as below shown way i'm getting response from server how can i get required one from that..
<data>
<limit>
<uname>android</uname>
<pwd>androiddeveloper</pwd>
<sessionid>abcdef56789ghijkl90a<sessionid/>
</limit>
</data>
I solved it from this link and is worked fine for me thanks to that guy who solved it.
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(inStream);
String playcount = "empty";
NodeList nl = doc.getElementsByTagName("playcount");
for(int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
playcount = nameElement.getFirstChild().getNodeValue().trim();
}
}
You can fire query for that. If the user is authenticated then get user's userId and store in some static variable.
This might you need i think.

parser 2.1 and 2.2

i using the follwing Code to retrive XML element text using getElementsByTagName
this code success in 2.2 and Failed in 2.1
any idea ?
URL metafeedUrl = new URL("http://x..../Y.xml")
URLConnection connection ;
connection= metafeedUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection ;
int resposnseCode= httpConnection.getResponseCode() ;
if (resposnseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf ;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the Earthquakes entry
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
//ArrayList<Album> Albums = new ArrayList<Album>();
/* Returns a NodeList of all descendant Elements with a given tag name, in document order.*/
NodeList nl = docEle.getElementsByTagName("entry");
if (nl!=null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element)nl.item(i);
/* Now on every property in Entry **/
Element title =(Element)entry.getElementsByTagName("title").item(0);
*Here i Get an Error*
String album_Title = title.getTextContent();
Element id =(Element)entry.getElementsByTagName("id").item(0);
String album_id = id.getTextContent(); //
getTextContent() is not supported in API 7 (Android 2.1). It was introduced in API 8 (2.2).
Assuming a predictable result from the server, you can use the following code:
Node n = aNodeList.item(i);
String strValue = n.getFirstChild().getNodeValue();
// as opposed to the String strValue = n.getTextContent();
If the element may be empty, then you'd want to check the child count first.

How to solve SAXParseExecption in android?

I am developing an application,In my application,I am displaying lot of images from url using DOM xml parsing,It is working fine,but some time i got org.xml.sax.SAXParseException: Unexpected end of the documentin my xml parsing handler.How to solve this problem,please help me.This is my xml parsing handler code
public String parse_bannerlink() throws UnknownHostException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String bannerlink=null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
org.w3c.dom.Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("partypicbanner");
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("link")) {
bannerlink=property.getFirstChild().getNodeValue();
}
}}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return bannerlink;
}
Thanks all
Try to validate your input file with any xml-validator, for example this: Xml validator
You are definitely not parsing that document using DOM you are parsing it using SAX. I'd check the document you are trying to parse as apparently that document is not valid.
UPDATE: Apparently I was wrong. Didn't know that DOM throws that exception too.

Categories

Resources