Android的HTTP通信 XML解析和异步消息处理
2010-02-03 19:10:00 来源:WEB开发网textView.append(" name: "+name+" salary: "+salary+" dateOfBirth: " + dateOfBirth);
}
} catch (Exception e) {
textView.setText(e.toString());
}
}
// 以 SAX 方式解析 XML(xml 数据详见 res/raw/employee.xml)
// SAX 解析器的实现详见 MySAXHandler.java
private void SAXDemo(){
try {
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser parser = saxFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
MySAXHandler handler = new MySAXHandler();
reader.setContentHandler(handler);
reader.parse(new InputSource(this.getResources().openRawResource(R.raw.employee)));
String result = handler.getResult();
textView.setText("SAXDemo" + " ");
textView.append(result);
} catch (Exception e) {
textView.setText(e.toString());
}
}
// 辅助方法,用于把流转换为字符串
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + " ");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
2、用 Handler 来实现异步消息处理,以一个可以实时汇报下载进度的异步下载类为例
开发一个 Android 类库,本例中此类库名为 webabcd_util
New -> Java Project
更多精彩
赞助商链接