0
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();
}
}
完成这项工作并不需要很长时间,所以考虑模拟器的速度有多慢,getxmlfromurl的权限必然会出错。我得到的输出在我的TextView从url中获取xml不起作用
[email protected]
我的网址是调用getXMLFromUrl IV前细右测试的。
我刚刚更改了xmlFromUrl,现在可以工作。而且你的右边也跟着toString(),iv只是记录了event.getName,并且按照预期发布。 我有点困惑为什么toString()不工作,虽然? – nicwhitts