Android异常 java.lang.IllegalStateException解决方法
Android异常详情介绍
这种异常我遇到以下两种情况:
1.java.lang.IllegalStateException:Nowrappedconnection.
2.java.lang.IllegalStateException:Adapterisdetached.
原因:
1.单线程一次执行一个请求可以正常执行,如果使用多线程,同时执行多个请求时就会出现连接超时.
2.HttpConnection没有连接池的概念,多少次请求就会建立多少个IO,在访问量巨大的情况下服务器的IO可能会耗尽。
3.通常是因为HttpClient访问单一实例的不同的线程或未关闭InputStream的httpresponse。
解决方案:获得httpclient线程安全
解决前代码:
publicHttpClienthttpClient=newDefaultHttpClient();
publicvoidpostNoResult(finalContextcontext,finalStringurl,finalMap<String,String>maps,finalStringshow){
newThread(){
@Override
publicvoidrun(){
try{
HttpPostpost=newHttpPost(url);
List<NameValuePair>params=newArrayList<NameValuePair>();
for(Stringkey:maps.keySet()){
params.add(newBasicNameValuePair(key,maps.get(key)));
}
post.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponseresponse=httpClient.execute(post);//报错位置
if(response.getStatusLine().getStatusCode()==200){
Looper.prepare();
Stringr=EntityUtils.toString(response.getEntity());
ToastUtil.print_log(r);
if(show!=null){
ToastUtil.show(context,show);
}
Looper.loop();}
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}}}.start();
}
解决后代码:
publicHttpClienthttpClient=getThreadSafeClient();//获得httpclient线程安全。
publicstaticDefaultHttpClientgetThreadSafeClient(){
//获得httpclient线程安全的方法
DefaultHttpClientclient=newDefaultHttpClient();
ClientConnectionManagermgr=client.getConnectionManager();
HttpParamsparams=client.getParams();
client=newDefaultHttpClient(newThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()),params);
returnclient;
}
publicvoidpostNoResult(finalContextcontext,finalStringurl,finalMap<String,String>maps,finalStringshow){
newThread(){
@Override
publicvoidrun(){
try{
HttpPostpost=newHttpPost(url);
List<NameValuePair>params=newArrayList<NameValuePair>();
for(Stringkey:maps.keySet()){
params.add(newBasicNameValuePair(key,maps.get(key)));
}
post.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponseresponse=httpClient.execute(post);//报错位置
if(response.getStatusLine().getStatusCode()==200){
Looper.prepare();
Stringr=EntityUtils.toString(response.getEntity());
ToastUtil.print_log(r);
if(show!=null){
ToastUtil.show(context,show);
}
Looper.loop();}
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}}}.start();
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便