您好,登錄后才能下訂單哦!
我也是剛剛接觸程序開發,一個菜鳥。前面和幾個同學準備做一個移動教務系統,網上看了很多資料都說了對運行一些費時。如數據庫、網絡的鏈接操作,需要新開一個thread對其進行處理。但是后面在對程序進行調試的過程中,剛開始的時候報了空指針錯誤。根據錯誤提示,進行修改。說實話,經過那個過程發現自己真的還很菜,排錯的經驗太少了。直到過了好久才想到報了空指針錯誤,是因為在線程里生成的對象,因為有時間延遲,對于線程后面的對象來說是空的,所以才導致了空指針錯誤。后面參考的解決方法是利用join()函數。當然也可用其他方法。
下面寫的代碼:
public class MyThread extends Thread { private InputStream is = null; private String url; private String method; private List<NameValuePair> params; public MyThread(String url, String method, List<NameValuePair> params) { this.method = method; this.url = url; this.params = params; } public void run() { try { // check for request method if (method.equals("POST")) { // request method is POST // defaultHttpClient BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) HttpConnectionParams .setConnectionTimeout(httpParameters, 30000); // in milliseconds which is the timeout for waiting for // data. HttpConnectionParams.setSoTimeout(httpParameters, 30000); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); setIs(httpEntity.getContent()); } else if (method.equals("GET")) { BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) HttpConnectionParams .setConnectionTimeout(httpParameters, 30000); // in milliseconds which is the timeout for waiting for // data. HttpConnectionParams.setSoTimeout(httpParameters, 30000); // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); String temp_url = url + "?" + paramString; HttpGet httpGet = new HttpGet(temp_url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); setIs(httpEntity.getContent()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public InputStream getIs() { return is; } public void setIs(InputStream is) { this.is = is; } }
通過下面的語句對以上生成的對象(“setIs(httpEntity.getContent());
“)進行調用
MyThread myThread = new MyThread(url, method, params); myThread.start(); myThread.join();//同做join()函數對myThread進行處理,使其一般的對象那樣使用即可 is = myThread.getIs();//獲得is對象
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。