标签:
今天实际项目中遇到了这个问题,感觉自己代码真的一点问题都没有,从网上查了一下资料,基本上都是说不能把耗时的任务放在主线程,可是博主真的没有把耗时的任务放在主线程,好了废话不多说,先上代码,根据代码说问题:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
mDialog = ProgressDialog.show(getActivity(), "下载文件", "正在下载……");
Thread loadThread = new Thread(new LoadThread());
loadThread.start();
}
class LoadThread implements Runnable {
@Override
public void run() {
initData();
}
}
private void initData() {
HttpClient httpClient = new DefaultHttpClient();
HttpGet request;
try {
request = new HttpGet(new URI(FOSHIFUWU_API));
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String out = EntityUtils.toString(entity, "UTF-8");
buddhistServicesBeans.add(new BuddhistServicesBean(title, des, money, unitId, endDate));
// 博主刚开始把这个代码放在了这个子线程,而不是UI线程
// buddhistServicesAdapter = new BuddhistServicesAdapter(getActivity(), buddhistServicesBeans);
// buddhistservices_listview.setAdapter(buddhistServicesAdapter);
}
isNet = true;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
isNet = false;
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message msg = Message.obtain();
if (isNet) {
msg.what = 0;
handler.sendMessage(msg);
} else {
msg.what = 1;
handler.sendMessage(msg);
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
mDialog.cancel();
// 后来博主把这个放在了处理UI线程进行处理
buddhistServicesAdapter = new BuddhistServicesAdapter(getActivity(), buddhistServicesBeans);
buddhistservices_listview.setAdapter(buddhistServicesAdapter);
buddhistservices_listview.setOnItemClickListener(new bsInfoOnItemClickListener());
break;
case 1:
break;
}
}
};
相信根据代码的注释大家基本都懂了是什么原因了吧,简单来说,网络请求是耗时线程,但是把从网上解析到的json放在ListView上的却并不是耗时线程,而是主线程,就是UI的更新线程,所以就是说主线程和UI线程放在一起了,结果导致了这个原因,相信怎么解决问题大家就都知道了吧,子线程内都放子线程需要做的任务,而UI线程都应该是UI线程,这两个不能放在一起,希望对大家有所帮助,博主为此郁闷了一下午
Only the original thread that created a view hierarchy can touch its views
标签:
原文地址:http://blog.csdn.net/qq_23195583/article/details/44963207