2013-01-25 41 views
3

這裏全碼asyntask發送數據的Http強制關閉原因HTTP實體不可以爲null

private class MyAsyncTaskPupuk extends AsyncTask<Void,Object ,Void> { 

boolean bNodata=false; 
boolean bError=false; 
@Override 
protected Void doInBackground(Void... arg0) { 
    bNodata=false; 
    bError=false; 
    recordCount=cursorSend.getCount(); 
    if (recordCount<=0){// 
     bNodata=true; 
     return null; 
    } 
    cursorSend.moveToFirst(); 
    publishProgress(0,"Sending data started"); 
    //SystemClock.sleep(1000); 
    CHamaRecord rec=new CHamaRecord(); 
    for (int i=0; i<recordCount; i++){ 
     if (isCancelled()) break; 
     rec.lID=cursorSend.getLong(0); 
     rec.dLongitude=cursorSend.getDouble(1); 
     rec.dLatitude=cursorSend.getDouble(2); 
     rec.dAccuracy=cursorSend.getDouble(3); 
     rec.sFilename=cursorSend.getString(4); 
     rec.nUserId=cursorSend.getInt(5); 
     rec.nRate=cursorSend.getInt(6); 
     rec.lDate=cursorSend.getLong(7); 
     rec.sSent=cursorSend.getString(8); 
     rec.IDSite=cursorSend.getString(9); 
     rec.alamatSite=cursorSend.getString(10); 
     rec.komoditas=cursorSend.getString(11); 
     rec.luasSite=cursorSend.getString(12); 
     rec.petugas=cursorSend.getString(13); 
     rec.jnsHama=cursorSend.getString(14); 
     rec.jmlHama=cursorSend.getString(15); 
     rec.sn=cursorSend.getString(16); 
     rec.pn=cursorSend.getString(17); 
     rec.manufaktur=cursorSend.getString(18); 
     rec.lblHama=cursorSend.getString(19); 
     rec.lblKomoditas=cursorSend.getString(20); 
     rec.lblPetugas=cursorSend.getString(21); 
     publishProgress(1,i,rec); 
     if (!SendDataFoto(rec)){ 
      recordCount=i; 
      bError=true; 
      break; 
     } 
     else { 
      //change flag sent 
      rec.sSent=CGeneral.strSent; 
      cDBPupuk.updateEntry(rec.lID, rec); 
     } 
     cursorSend.moveToNext(); 
    } 
    return null; 
}//doInBackground 

private boolean SendDataFoto(CHamaRecord rec){ 


     String slon=String.format("%f", rec.dLongitude); 
     String slat=String.format("%f", rec.dLatitude); 
     String sacc=String.format("%f", rec.dAccuracy); 
     String srate=String.format("%d",rec.nRate); 
     String sid=String.format("%d",rec.nUserId); 
     String ids=String.format(rec.IDSite); 
     String alt=String.format(rec.alamatSite); 
     String kmd=String.format(rec.komoditas); 
     String ls=String.format(rec.luasSite); 
     String op=String.format(rec.petugas); 
     String jns=String.format(rec.jnsHama); 
     String jml=String.format(rec.jmlHama); 
     String sn=String.format(rec.sn); 
     String pn=String.format(rec.pn); 
     String mFact=String.format(rec.manufaktur); 
     String lblhama=String.format(rec.lblHama); 
     String lblKomoditas=String.format(rec.lblKomoditas); 

     File file=new File(rec.sFilename); 
     String sfname=file.getName(); 
     String cfname=file.getName(); 
     int i=0; 
     String lfname=rec.sFilename; 
     sfname = sfname.substring(0, sfname.lastIndexOf(".")); 
     Calendar cal=Calendar.getInstance(); 
     cal.setTime(new Date(rec.lDate)); 
     String sdat=CUtilities.DateToString(cal); 


     String url; 
     String spupuk; 
     if (CGeneral.nPupukOrPelihara==CGeneral.ACTIVITY_FOR_PUPUK){ 
      url = CGlobalConfig.getURLRcvrPupuk(); 
      spupuk="Hama"; 
     } 
     else{ 
      url = CGlobalConfig.getURLRcvrPeliharaImage(); 
      spupuk="pelihara"; 
     } 

     Bitmap bmp=BitmapFactory.decodeFile(lfname); 
     ByteArrayOutputStream bao = new ByteArrayOutputStream(); 

     bmp.compress(Bitmap.CompressFormat.JPEG, 90, bao); 

     byte[] ba = bao.toByteArray(); 

     HttpEntity entity=null; 

     try { 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      ByteArrayBody bab = new ByteArrayBody(ba, spupuk+"_"+cfname); 
      MultipartEntity reqEntity = new MultipartEntity(
      HttpMultipartMode.BROWSER_COMPATIBLE); 
      reqEntity.addPart("image", bab); 
      reqEntity.addPart("category", new StringBody(spupuk)); 
      reqEntity.addPart("file_name", new StringBody(spupuk+"_"+cfname)); 
      reqEntity.addPart("rate", new StringBody(srate)); 
      reqEntity.addPart("tgl", new StringBody(sdat)); 
      reqEntity.addPart("user_id", new StringBody(sid)); 
      reqEntity.addPart("latitude", new StringBody(slat)); 
      reqEntity.addPart("longitude", new StringBody(slon)); 
      reqEntity.addPart("accuracy", new StringBody(sacc)); 
      reqEntity.addPart("id_site", new StringBody(ids)); 
      reqEntity.addPart("alamat_site", new StringBody(alt)); 
      reqEntity.addPart("komoditas", new StringBody(kmd)); 
      reqEntity.addPart("luas_area", new StringBody(ls)); 
      reqEntity.addPart("petugas", new StringBody(op)); 
      reqEntity.addPart("jenis_hama", new StringBody(jns)); 
      reqEntity.addPart("jumlah_hama", new StringBody(jml)); 
      reqEntity.addPart("serial", new StringBody(sn)); 
      reqEntity.addPart("p_number", new StringBody(pn)); 
      reqEntity.addPart("manufaktur", new StringBody(mFact)); 

      httppost.setEntity(reqEntity); 
      HttpResponse response = httpclient.execute(httppost); 

      entity = response.getEntity(); 


     } catch (Exception e) { 
      Log.e(e.getClass().getName(), e.getMessage()); 
     } 
     String temp = null; 
     try { 
      temp = EntityUtils.toString(entity); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 



     if (temp.compareTo("SUCCESS") == 0) { 
      publishProgress(0,"Send Ok"); 
      SystemClock.sleep(500); 
      return true; 
     } 
     else{ 
      publishProgress(0,"Send Fail"); 
      return false;    
     } 

    } 

@Override 
    protected void onProgressUpdate(Object... arg) { 
     Integer oi=(Integer)arg[0]; 
     String oStr; 
     CHamaRecord rec; 
     int flag=oi.intValue(); 
     int nVal; 
     String str; 
     TextView tvStatus=(TextView) layoutSendDialog.findViewById(R.id.tvPupukSendStatus); 
     TextView tview; 
     switch (flag) { 
     case 0 : 
      oStr=(String)arg[1]; 
      tvStatus.setText(oStr); 
      break; 
     case 1 : 
      oi=(Integer)arg[1]; 
      rec=(CHamaRecord)arg[2]; 
      nVal=oi.intValue(); 
      str="Send record #"+String.format("%d",nVal); 
      tvStatus.setText(str); 
      str=String.format("%d", rec.lID); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendID); 
      tview.setText(str); 
      str=String.format(rec.IDSite); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendIDSite); 
      tview.setText(str); 
      str=String.format(rec.alamatSite); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendAlamat); 
      tview.setText(str); 
      str=String.format(rec.lblKomoditas); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendKomoditas); 
      tview.setText(str); 
      str=String.format(rec.luasSite); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendLuas); 
      tview.setText(str); 
      str=String.format(rec.lblPetugas); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendPetugas); 
      tview.setText(str); 
      str=String.format(rec.lblHama); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendJenis); 
      tview.setText(str); 
      str=String.format(rec.jmlHama); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendJumlah); 
      tview.setText(str); 
      str=String.format(rec.sn); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendSerial); 
      tview.setText(str); 
      str=String.format(rec.pn); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendProduk); 
      tview.setText(str); 
      str=String.format(rec.manufaktur); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendManufaktur); 
      tview.setText(str); 
      str=String.format("%+3.5f", rec.dLongitude); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendLongitude); 
      tview.setText(str); 
      str=String.format("%+3.5f", rec.dLatitude); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendLatitude); 
      tview.setText(str); 
      /*str=String.format("%2.2f", rec.dAccuracy); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendAccuracy); 
      tview.setText(str);*/ 
      Date dt=new Date(rec.lDate); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendDate); 
      tview.setText(dt.toLocaleString()); 
      /*str=String.format("%d", rec.nRate); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendRating); 
      tview.setText(str); 
      str=String.format("%d", rec.nUserId); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendOperator); 
      tview.setText(str); */ 
      File file=new File(rec.sFilename); 
      String fname=file.getName(); 
      tview = (TextView) layoutSendDialog.findViewById(R.id.tvPupukSendFilename); 
      tview.setText(fname); 
      break; 
     } 
    } 
    // 
    @Override 
    protected void onPostExecute(Void unused) { 
     TextView tvStatus=(TextView) layoutSendDialog.findViewById(R.id.tvPupukSendStatus); 
     if (bNodata){ 
      tvStatus.setText("No data to be sent!!!");    
     }else { 
      if (bError){ 
       tvStatus.setText("Fail at record #"+String.format("%d",recordCount)); 
      } 
      else { 
       tvStatus.setText("Sending Data : Finished"); 
      } 
     } 
//   dismissDialog(CGeneral.DIALOG_SEND); 
    } 
    protected void onCancelled(Void unused) { 
     dismissDialog(CGeneral.DIALOG_SEND); 
    } 

} 

應用工作,但是當我把錯誤的URL或連接超時 ,應用程序強制關閉。

,這裏是我的logcat

01-25 10:11:27.554: ERROR/AndroidRuntime(2587): FATAL EXCEPTION: AsyncTask #1 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587): java.lang.RuntimeException: An error occured while executing doInBackground() 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at android.os.AsyncTask$3.done(AsyncTask.java:200) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.util.concurrent.FutureTask.setException(FutureTask.java:125) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.util.concurrent.FutureTask.run(FutureTask.java:138) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.lang.Thread.run(Thread.java:1019) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587): Caused by: java.lang.IllegalArgumentException: HTTP entity may not be null 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at org.apache.http.util.EntityUtils.toString(EntityUtils.java:110) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at hariff.ltis.inputhama.CInputHamaApp$MyAsyncTaskPupuk.SendDataFoto(CInputHamaApp.java:1307) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at hariff.ltis.inputhama.CInputHamaApp$MyAsyncTaskPupuk.doInBackground(CInputHamaApp.java:1040) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at hariff.ltis.inputhama.CInputHamaApp$MyAsyncTaskPupuk.doInBackground(CInputHamaApp.java:1) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at android.os.AsyncTask$2.call(AsyncTask.java:185) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 
01-25 10:11:27.554: ERROR/AndroidRuntime(2587):  ... 4 more 
01-25 10:11:27.570: DEBUG/u-blox(1308): ublox_stop : 
01-25 10:11:27.570: WARN/ActivityManager(1308): Force finishing activity hariff.ltis.mainmenu/hariff.ltis.inputhama.CInputHamaApp 

力接近線temp = EntityUtils.toString(entity);

如何解決呢?所以當我把錯誤的網址或連接超時,應用程序不強制關閉並顯示消息"Send Failed"。 ?

BR

亞歷

+0

你有把互聯網權限清單文件 –

+0

是的,之前我把真正的網址,它的工作原理。但現在當我使用錯誤的網址或超時時,問題是強制關閉。 –

+0

異常很清楚,實體傳入[EntityUtils.toString()](http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpcore/4.0-beta2/org /apache/http/util/EntityUtils.java#106)爲NULL。在調用'temp = EntityUtils.toString(entity)之前檢查該值;' – yorkw

回答

3

你有一個HttpResponse那裏,檢查您嘗試使用實體之前。

http://developer.android.com/reference/org/apache/http/HttpResponse.html

int code = response.getStatusLine().getStatusCode(); 
String message = response.getStatusLine().getReasonPhrase(); 

這裏是Apache使用的代碼常數(他們是標準的HTTP,但因爲你是使用HttpClient您可以參考這些,看看你有你期望的迴應,或不):http://developer.android.com/reference/org/apache/http/HttpStatus.html

如果請求到達服務器並失敗,響應會讓你知道(對於「錯誤的URL」,如甚至沒有解析主機,連接將超時,但這不是錯誤你越來越)。而且,即使在那之後,我相信你仍然應該在將它傳遞給EntityUtils之前檢查該實體是否爲空(如果它爲空,那麼其他意想不到的事情會出錯)。這個例子應該指向正確的方向(我不建議只是複製/粘貼它,而是試圖理解它;這是一個廣泛的概括,你可能想要檢查標準的OK響應,不是重定向,而或您的服務器端,可以做一些非標準的,這取決於在服務器上):

HttpResponse httpResponse = null; 
    String response = null; 
    String message = null; 
    int code = -1; 
    try { 
    httpResponse = client.execute(request); 
    code = httpResponse.getStatusLine().getStatusCode(); 
    message = httpResponse.getStatusLine().getReasonPhrase(); 

    Log.i("LOG_TAG", "HTTP response -- code:" + code + " message:" + message); 

    if (code >= 200 && code <= 399) { 
     Log.v("LOG_TAG", "got valid HTTP response code (200-399) processing response entity"); 
     HttpEntity entity = httpResponse.getEntity(); 
     if (entity != null) { 
      InputStream instream = null; 
      try { 
       instream = entity.getContent(); 
       // convert stream if gzip header present in response 
       Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding"); 
       if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
       instream = new GZIPInputStream(instream); 
       } 
       response = convertStreamToString(instream); 
      } finally { 
       if (instream != null) { 
       instream.close(); 
       } 
      } 
     } 
    } else { 
     // GOT SOME NON-VALID CODE, 404 (not found), 5xx (error), etc (log this, react to this, whatever, but you can't just use the "entity") 
    } 
    } catch (ClientProtocolException e) { 
    throw new RuntimeException("ERROR:" + e.getMessage(), e); 
    } catch (IOException e) { 
    throw new RuntimeException("ERROR:" + e.getMessage(), e); 
    } finally { 
    // shutdown connections 
    client.getConnectionManager().shutdown(); 
    } 

在200和399之間的普通的HTTP響應代碼是成功或重定向,以及4XX,5XX是錯誤的。以下是有關HTTP響應代碼的更多信息:http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

+0

你能給我一個示例代碼嗎?即時通訊新手在Android。 @Charlie Collins –

+0

我會更新答案... –

+0

我已經更新了答案,包括一個更具體的例子,說明如何在您嘗試從中獲取實體時檢查HttpResponse狀態代碼和消息(您不能只獲取實體,如果發生某些情況請求錯誤或服務器錯誤等)。 –

0

您可以通過以下代碼保持請求超時和套接字異常。

try{ 
    HttpParams httpParams = new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(httpParams, 20000); 
    HttpConnectionParams.setSoTimeout(httpParams, 20000); 
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); 

     ................................. 
     .................................. 
      ................................... 

      httppost.setEntity(reqEntity); 
      HttpResponse response = httpclient.execute(httppost); 

      entity = response.getEntity(); 



     }catch(ConnectTimeoutException e){ 
       //Do whatever you want here when you get timeout in connection 
     }catch(SocketTimeoutException scte){ 
       // Do whatever you want here when you get sockettimeout exception... 

     }catch(Exception e){ 
     //Do whatever you want here when you get unexpected exception... It is root exception . So whatever exception you didn't catch in the above, the control obviously gets into this block. 
} 

即使您可以在catch塊中返回任何您想要的默認結果。

+0

使用其他合理的設置也是一個好主意,但他使用的DefaultHttpClient已經有了一些合理的默認值。而且,他已經有了發言權(儘管最終沒有結束,但這是一個不同的問題)。超時和異常不是問題,他只是試圖在沒有實體的時間和地點使用實體。 –

+0

我添加yor代碼,但仍然強制關閉:http可能不會爲空行'temp = EntityUtils.toString(實體);' –

+0

@CharlieCollins是的。你是對的。當他最後要求暫停時,我已經證明了這個例外。 +1如果問題仍然未知,那麼當您的實體爲空時,您的答案可以很好地處理所有其他問題,並且他可以排除它。 – Kanth