开启多线程之后,相当于并行执行,所以线程的run方法和原程序一样对待,并非先执行run,忽略此问题容易导致数组越界
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == UPDATE) {
//用户点击了更新按钮
//http请求必须使用线程处理
HttpDownLoad httpDownLoad = new HttpDownLoad();
httpDownLoad.start();
String xml = downloadXML("http://192.168.0.101:8080/mp3/resources.xml");
List<Mp3Info> mp3Infos = parse(xml);
//设定循环,保证线程里面的run方法先执行完成,以防httpDownLoad.list为空
//线程run执行的循环要比顺序执行SimpleAdapter显然要慢
while(httpDownLoad.list.size() < mp3Infos.size()){
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, httpDownLoad.list, R.layout.mp3info_item, new String[]{"mp3_name", "mp3_size"},new int[]{R.id.mp3_name,R.id.mp3_size});
setListAdapter(simpleAdapter);
return true;
}else if(id == ABOUT){
//用户点击了关于按钮
}
return super.onOptionsItemSelected(item);
}
private class HttpDownLoad extends Thread{
List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
public void run() {
// TODO Auto-generated method stub
String xml = downloadXML("http://192.168.0.101:8080/mp3/resources.xml");
List<Mp3Info> mp3Infos = parse(xml);
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);
}
}
}