Android异常java.lang.IllegalStateException解决方法

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Android异常ng.IllegalStateException解决⽅法Android异常详情介绍
这种异常我遇到以下两种情况:
1. ng.IllegalStateException: No wrapped connection.
ng.IllegalStateException: Adapter is detached.
原因:
1.单线程⼀次执⾏⼀个请求可以正常执⾏,如果使⽤多线程,同时执⾏多个请求时就会出现连接超时.
2.HttpConnection没有连接池的概念,多少次请求就会建⽴多少个IO,在访问量巨⼤的情况下服务器的IO可能会耗尽。

3.通常是因为HttpClient访问单⼀实例的不同的线程或未关闭InputStream的httpresponse。

解决⽅案:获得httpclient线程安全
解决前代码:
public HttpClient httpClient = new DefaultHttpClient();
public void postNoResult(final Context context, final String url, final Map<String, String> maps, final String show) {
new Thread() {
@Override
public void run() {
try {
HttpPost post = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
params.add(new BasicNameValuePair(key, maps.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = httpClient.execute(post);//报错位置
if (response.getStatusLine().getStatusCode() == 200) {
Looper.prepare();
String r = EntityUtils.toString(response.getEntity());
ToastUtil.print_log(r);
if (show != null) {
ToastUtil.show(context, show);
}
Looper.loop();}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}}}.start();
}
解决后代码:
public HttpClient httpClient = getThreadSafeClient();//获得httpclient线程安全。

public static DefaultHttpClient getThreadSafeClient() {
//获得httpclient线程安全的⽅法
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
public void postNoResult(final Context context, final String url, final Map<String, String> maps, final String show) {
new Thread() {
@Override
public void run() {
try {
HttpPost post = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
params.add(new BasicNameValuePair(key, maps.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = httpClient.execute(post);//报错位置
if (response.getStatusLine().getStatusCode() == 200) {
Looper.prepare();
String r = EntityUtils.toString(response.getEntity());
ToastUtil.print_log(r);
if (show != null) {
ToastUtil.show(context, show);
}
Looper.loop();}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}}}.start();
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

相关文档
最新文档