public class GetXMLTask extends AsyncTask<String, Void, String> {
// XML node names
static final String NODE_EVEN = "event";
static final String NODE_NAME = "name";
static final String NODE_DATE = "date";
static final String NODE_LOC = "location";
private TextView txtView;
public GetXMLTask(TextView txtView) {
this.txtView = txtView;
}
@Override
protected String doInBackground(String... urls) {
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
}
return xml;
}
@Override
protected void onPostExecute(String xml) {
XMLDOMParser parser = new XMLDOMParser();
InputStream stream = new ByteArrayInputStream(xml.getBytes());
Document doc = parser.getDocument(stream);
NodeList nodeList = doc.getElementsByTagName(NODE_EVEN);
ArrayList<Event>events = new ArrayList<Event>();
Event event = new Event();
for (int i = 0; i < nodeList.getLength(); i++) {
// event = new Event();
Element e = (Element) nodeList.item(i);
//will use for something later on
event.setName(parser.getValue(e, NODE_NAME));
//event.setName(parser.getValue(e, NODE_DATE));
event.setName(parser.getValue(e, NODE_LOC));
events.add(event);
}
txtView.setText(doc.toString()); // to test xml!
}
/* uses HttpURLConnection to make Http request from Android to download
the XML file */
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
InputStream stream = null;
URL url;
try {
url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (MalformedURLException e) {
Log.e("Error", "Unable to parse URL", e);
} catch (IOException e) {
Log.e("Error", "IO Exception", e);
}
return output.toString();
}
}
It doesn't take that long to complete so considering how slow the emulator is something must be going wrong with the getxmlfromurl right? i get output in my textview
org.apache.harmony.xml.dom.DocumentImpl@b3d5c4b0
My url is fine right before calling getXMLFromUrl iv tested that.