Android异常java.lang Android异常 java.lang.IllegalStateException解决办法
DeMon辉 人气:7想了解Android异常 java.lang.IllegalStateException解决办法的相关内容吗,DeMon辉在本文为您仔细讲解Android异常java.lang的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android异常java.lang,下面大家一起来学习吧。
Android异常详情介绍
这种异常我遇到以下两种情况:
1. java.lang.IllegalStateException: No wrapped connection.
2.java.lang.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(); }
加载全部内容