问题描述
- Android下载解析xml文件ListView中数据无法更新,要添加一个线程应该可以。求帮助
-
我用的Android4.1的手机和Android4.2的模拟器,项目可以正常运行,没有报错,就是下载xml文件解析的数据无法正常显示到Listview中。之前用了个Thread()的可以下载解析xml,不用Thread()的话,就无法下载解析XML中数据,但是在Listview中使用Thread()又要报错了。
@Override
public boolean onOptionsItemSelected(MenuItem item) {if (item.getItemId() == UPDATE) { //用户点击了 更新列表 按钮 //new Thread(){ //public void run(){ updateListView(); //} //}.start(); } else if (item.getItemId() == ABOUT) { //用户点击了 关于 按钮 } return super.onOptionsItemSelected(item); } private SimpleAdapter buildSimpleAdapter(List<Mp3Info> mp3Infos) { // 生成一个List对象,并按照SimpleAdapter的标准,将mp3Infos当中的数据添加到List当中去 List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) { Mp3Info mp3Info = (Mp3Info) iterator.next(); HashMap<String, String> map = new HashMap<String, String>(); map.put("mp3_name", mp3Info.getMp3Name()); map.put("mp3_size", mp3Info.getMp3Size()); list.add(map); } // 创建一个SimpleAdapter对象 SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, R.layout.mp3info_item, new String[] { "mp3_name", "mp3_size" }, new int[] { R.id.mp3_name, R.id.mp3_size }); // 将这个SimpleAdapter对象设置到ListActivity当中 return simpleAdapter; } private void updateListView() { // 用户点击了更新列表按钮 // 下载包含所有Mp3基本信息的xml文件 String xml = downloadXML("http://59.69.26.186:8080/mp3/resources.xml"); // 对xml文件进行解析,并将解析的结果放置到Mp3Info对象当中,最后将这些Mp3Info对象放置到List当中 mp3Infos = parse(xml); SimpleAdapter simpleAdapter = buildSimpleAdapter(mp3Infos); setListAdapter(simpleAdapter); } private String downloadXML(String urlStr){ HttpDownloader httpDownloader = new HttpDownloader(); String result = httpDownloader.download(urlStr); return result; } private List<Mp3Info> parse(String xmlStr){ SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); List<Mp3Info> infos = new ArrayList<Mp3Info>(); try { XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader(); Mp3ListContentHandler mp3ListContentHandler = new Mp3ListContentHandler(infos); xmlReader.setContentHandler(mp3ListContentHandler); xmlReader.parse(new InputSource(new StringReader(xmlStr))); for (Iterator iterator = infos.iterator(); iterator.hasNext();) { Mp3Info mp3Info = (Mp3Info) iterator.next(); System.out.println(mp3Info); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return infos; }
}
时间: 2024-11-01 19:39:37