Reputation: 37
I'm trying to parse an xml file that I get by entering the url of that xml file as a parameter in my doInBackground function. Now I call this function 2 times.
During the first call it works fine.
During the second call it gives me a parsing error:
08-16 23:49:20.823 27735-28009/be.project.randomreader W/System.err﹕ org.xml.sax.SAXParseException: Unexpected token (position:TEXT {"success":{"tot...@1:210 in java.io.InputStreamReader@9e143cb)
Does it have to do something with the "?" sign and the "=" sign in my url?
How can I change my code to resolve this problem?
//first call:
ArrayList<String> url= new ArrayList<String>();
url.add("http://api.theysaidso.com/qod.xml");
url.add("");
new DownloadXML().execute(url);
//second call after a click event:
ArrayList<String> url= new ArrayList<String>();
url.add("http://api.theysaidso.com/");
url.add("qod?category=" + random);
new DownloadXML().execute(url);
private class DownloadXML extends AsyncTask<ArrayList<String>,Void,ArrayList> {
@Override
protected ArrayList doInBackground(ArrayList<String>... url) {
try {
ArrayList<String> urlLijst = url[0];
String query = URLEncoder.encode(urlLijst.get(1), "utf-8");
String url1 = urlLijst.get(0) + query;
URL url2 = new URL(url1); //.toString()
URLConnection conn = url2.openConnection();
DocumentBuilderFactory factory = documentBuilderFactor.get();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(conn.getInputStream());
parser.reset();
NodeList nodes = doc.getElementsByTagName("quotes");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("quote");
Element quote = (Element) title.item(0);
lijstQuotes.add(quote.getTextContent());
}
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("author");
Element author = (Element) title.item(0);
lijstQuotes.add(author.getTextContent());
}
}
}
}
Upvotes: 0
Views: 453
Reputation: 1152
Change your second call from
url.add("http://api.theysaidso.com/");
url.add("qod?category=" + random);
to
url.add("http://api.theysaidso.com/qod.xml?category=" + random);
theysaidso API seems to change its encoding based on the headers sent or explicit format request. By appending .xml you are forcing the format to be xml. In the other case you are getting back a json response and the parser fails. More info here https://theysaidso.com/api
Upvotes: 1
Reputation: 32
In the first call your
url[0] = "http://api.theysaidso.com/qod.xml"
In the second just:
"http://api.theysaidso.com/"
So, you didn't get the XML second time.
Try to change
url.add("http://api.theysaidso.com/");
url.add("qod?category=" + random);
into
url.add("http://api.theysaidso.com/qod?category=" + random);
url.add("");
Upvotes: 0