2016-06-11 168 views
0

我有一個異步任務,不斷向服務器發送消息並接收消息作爲回報。當我測試它時,我讓它運行幾秒鐘,然後關掉wifi。該應用程序然後崩潰併發送空指針異常。我能夠在HTTPPost中做任何事情,或者只是在沒有互聯網而不是崩潰應用程序的情況下發送消息?Android HTTP Post返回null

這是我的代碼

private class UpdateLoc extends AsyncTask<Void,Void,String> { 
     InputStream inputStream = null; 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      try{ 
       if(s.trim()!=null){ 
        Log.d("HTTPRESULT",s.toString()); 
       } 
      }catch (Exception e){ 
       e.printStackTrace(); 
      } 

     } 

     @Override 
     protected String doInBackground(Void... params) { 
      String result = null; 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(Constants.UPDATE); 
      List<NameValuePair> nameValuePairs = new ArrayList<>(); 
      nameValuePairs.add(new BasicNameValuePair(Constants.params_email,email)); 
      nameValuePairs.add(new BasicNameValuePair(Constants.params_location,curr_location)); 

      try{ 
       httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       inputStream = httpEntity.getContent(); 

       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"),8); 
       StringBuilder stringBuilder = new StringBuilder(); 
       String line = null; 
       while((line=bufferedReader.readLine())!=null){ 
        stringBuilder.append(line+"\n"); 
       } 
       result = stringBuilder.toString(); 

      }catch (ClientProtocolException e){ 
       e.printStackTrace(); 
      }catch (UnsupportedEncodingException e){ 
       e.printStackTrace(); 
      }catch (IOException e){ 
       e.printStackTrace(); 
      } 

      return result; 
     } 
    } 
+1

在調用任務之前運行互聯網連接檢查? – SQLiteNoob

+0

會減慢應用程序的速度嗎?我想每5秒鐘調用一次。 – JianYA

+0

也正如你已經捕捉到一些例外。你爲什麼不對NullPointerException做同樣的事情? – Salem

回答

0

嘗試調用AsyncTask前檢查網絡連接,是這樣的:

private boolean isNetworkAvailable() { 
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
} 

=======

你可以找到文檔here

+0

問題是,這在某些情況下不起作用吧?就像我連接到網絡但沒有互聯網連接一樣。 – JianYA

+0

它檢查您的手機是否有網絡連接 - 「activeNetworkInfo」只是告訴你,如果你的設備有WiFi等連接 - 唯一的方法來知道,如果你有一個適當的互聯網連接是從該網站獲得一個令牌,重新嘗試連接。我的3G總是說已連接,並且經常在Chrome中瀏覽錯誤。 – SQLiteNoob