2013-09-25 27 views
0

我得到異常時的AsyncTask從主要業務獲取異常時的AsyncTask從主要業務

下面的功能,我打電話給我的AsyncTask名爲「serverConnectorTask」類 在jsonResponse變量稱爲叫我需要得到的迴應這是從的AsyncTask得到

public void CreateJsonConnectNParseResponse(String stringtxtUserName, String hashedPwd ){ 
    jsonRequest = CONNECTOR.CreateJsonRequestLoginAction(stringtxtUserName,hashedPwd); 
    Log.d("LoginJsonRequest", jsonRequest); 
    //jsonResponse = CONNECTOR.jsonServerRequest(jsonRequest,ipaddress); 

    MyAsyncTask serverConnectorTask= new MyAsyncTask(getApplicationContext(),"ServerConnectorTask"); 
    serverConnectorTask.execute(jsonRequest); 
    Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST aftr task "); 
    jsonResponse=serverConnectorTask.jsonResult; 
    Log.d("JSON_SERVER_REQUEST", jsonResponse); 

    } 

我serverConnectorTask類如下圖所示:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 


import android.app.ProgressDialog; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.Toast; 

    public class MyAsyncTask extends AsyncTask<String, Void, String>{ 
Context context; 
private String name; 

    public HttpClient httpclient = new DefaultHttpClient(); 
    public HttpPost httppost; 
    public static String ipaddress; 
    public static String deviceID; 
    public String jsonResult = null ; 
    public ProgressDialog Dialog; 

public MyAsyncTask(Context mcontext,String name) { 
     context = mcontext; 
     this.name = name; 
     this.jsonResult=null; 
     Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST FUNCTION ENTERED 1"); 

} 


protected void onPreExecute() { 
    // NOTE: You can call UI Element here.   
     //Start Progress Dialog (Message) 
    Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST FUNCTION ENTERED 2"); 

     } 


// Call after onPreExecute method 
@Override 
protected String doInBackground(String... jsonrequest) { 

    /************ Make Post Call To Web Server ***********/ 


    Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST FUNCTION ENTERED "); 
     //String uri = "http://192.168.2.58:888/root/Calculator.Add"; 
     String uri=MainActivity.ipaddress;  
     httppost = new HttpPost(uri); 


     try { 
      Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST FUNCTION ENTERED IN TRY CATCH"); 
      StringEntity se = new StringEntity(jsonrequest[0]); 
      se.setContentType("application/json; charset=UTF-8"); 
      //se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8")); 

      httppost.setEntity(se); 
      httppost.setHeader("Accept", "application/json, text/javascript, */*"); 
      httppost.setHeader("Content-Type", "application/json; charset=utf-8"); 
      //httppost.setHeader("Keep-Alive", "true"); 
      HttpResponse response = httpclient.execute(httppost);     
      jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); 
      Log.d("JSON_SERVER_REQUEST", jsonResult); 
      } 

     catch (ClientProtocolException e) { 
      e.printStackTrace(); 
      Log.d("JSON_SERVER_REQUEST_CATCH", "Error in http connection " + e.toString()); 
      return null; 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
      Log.d("JSON_SERVER_REQUEST_CATCH", "Error in http connection " + e.toString()); 
      return null; 
     } 
    /*****************************************************/ 
    return jsonResult; 
} 
@Override 
protected void onPostExecute(String result) { 
    // NOTE: You can call UI Element here.  

    Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST onpost execute " +result); 
    //showMessage(jsonResult) ; 
    //Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST onpost execute "); 
    this.jsonResult=result; 
     } 


private void showMessage(String message) {   
    Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); 
    toast.show(); 
} 

private StringBuilder inputStreamToString(InputStream is) { 
     String rLine = ""; 
     StringBuilder jsonServerData = new StringBuilder(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is));  
     try { 
     while ((rLine = rd.readLine()) != null) { 
     jsonServerData.append(rLine); 
     } 
     }  
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     //Log.d("jsonresponse from server:", jsonServerData.toString()); 
     return jsonServerData;  
    } 

     } 

倍兒流量是我的例外,我得到的,

 09-25 14:26:14.720: E/AndroidRuntime(7804): FATAL EXCEPTION: main 
     09-25 14:26:14.720: E/AndroidRuntime(7804): java.lang.NullPointerException: println needs a message 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at android.util.Log.println_native(Native Method) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at android.util.Log.d(Log.java:137) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.kits.ddf.MainActivity.CreateJsonConnectNParseResponse(MainActivity.java:375) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.kits.ddf.MainActivity.doLoginaction(MainActivity.java:284) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.kits.ddf.MainActivity$4.onEditorAction(MainActivity.java:242) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at android.widget.TextView.onEditorAction(TextView.java:3297) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:102) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:297) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at android.os.Handler.dispatchMessage(Handler.java:99) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at android.os.Looper.loop(Looper.java:132) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at android.app.ActivityThread.main(ActivityThread.java:4025) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at java.lang.reflect.Method.invokeNative(Native Method) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at java.lang.reflect.Method.invoke(Method.java:491) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 
     09-25 14:26:14.720: E/AndroidRuntime(7804):  at dalvik.system.NativeStart.main(Native Method) 
+0

你究竟在哪裏得到錯誤(在你的代碼中)? – Izmaki

回答

0

使用這樣一個線程:

Thread thread = new Thread(new Runnable() { 
       @Override 
       public void run() { 
        try { 
             //do      

        } 
        }.start(); 
+1

I通過這樣做解決: \t MyAsyncTask serverConnectorTask = new MyAsyncTask(MainActivity.this,MainActivity.this,「ServerConnectorTask」); \t //serverConnectorTask.execute(jsonRequest); \t嘗試{ \t \t \t jsonResponse = serverConnectorTask.execute(jsonRequest).get(); \t \t}趕上(InterruptedException的E5){ \t \t \t // TODO自動生成的catch程序塊 \t \t \t e5.printStackTrace(); \t \t}趕上(爲ExecutionException E5){ \t \t \t // TODO自動生成的catch程序塊 \t \t \t e5.printStackTrace(); \t \t} \t \t \t Log.d( 「JSON_SERVER_REQUEST」, 「服務器請求AFTR任務」 + jsonResponse); –

0

在該方法中CreateJsonConnectNParseResponse

改變這一行

Log.d("JSON_SERVER_REQUEST", jsonResponse); 

是這樣

Log.d("JSON_SERVER_REQUEST", "" + jsonResponse); 

我想這隻會修復您當前擁有的NullPointerException,並且您可能會遇到更多問題。讓我們逐個修復它們。

+1

jsonResonse是一個字符串,所以不需要連接, 當我嘗試像這樣: \t serverConnectorTask.execute(jsonRequest); \t Log.d(「JSON_SERVER_REQUEST」,「SERVER REQUEST aftr task」); \t jsonResponse = serverConnectorTask.jsonResult;如果(jsonResponse!= null){ \t \t Log.d(「JSON_SERVER_REQUEST」,jsonResponse); \t \t} \t 沒有厚望,但我不得到jsonResponse在CreateJsonConnectNParseResponse()的值 –

+0

你正在發生時,'jsonResponse'是空的空指針異常。通過將它與一個空字符串連接起來,可以確保它永遠不會發生。那麼讓我們來看看爲什麼你不能從AsyncTask中獲得價值。 –

+0

我已初始化變量,問題是我不是從MyAsyncTask類到我的CreateJsonConnectNParseResponse()函數獲取值jsonResponse。在我的MyAsyncTask中,我能夠獲取值,但MyAsyncTask滯後於iam,當我調用jsonResponse = serverConnectorTask時無法獲取值。jsonResult;所以我需要知道線程是完整的,以便我可以調用jsonResponse = serverConnectorTask.jsonResult;如何做到這一點?任何想法? –

0

根據文檔here

你需要傳遞字符串參數的log.d方法。可能,變量jsonResponse爲空。 確保在傳遞log.d方法之前將json響應轉換爲字符串

0

此行可能會給出錯誤Log.d("JSON_SERVER_REQUEST", jsonResponse);因爲您試圖用NULL值打印日誌。請嘗試初始化變量。 例如:​​

+0

我已初始化變量,問題是我不是從MyAsyncTask類到我的CreateJsonConnectNParseResponse()函數的獲取值jsonResponse。 在我MyAsyncTask我能夠得到的價值,但作爲MyAsyncTask滯後iam無法獲得值,當我調用jsonResponse = serverConnectorTask.jsonResult; 所以我需要知道線程是否完整,以便我可以調用 jsonResponse = serverConnectorTask.jsonResult;如何做到這一點?任何想法? –

0

我通過serverConnectorTask.execute(jsonRequest).get()解決了這個問題,這將使進程等待,如果計算完成需要等待,然後檢索其結果。

MyAsyncTask serverConnectorTask= new MyAsyncTask(MainActivity.this,MainActivity.this,"ServerConnectorTask"); 
    //serverConnectorTask.execute(jsonRequest); 
    try { 
     jsonResponse=serverConnectorTask.execute(jsonRequest).get(); 
    } catch (InterruptedException e5) { 
     // TODO Auto-generated catch block 
     e5.printStackTrace(); 
    } catch (ExecutionException e5) { 
     // TODO Auto-generated catch block 
     e5.printStackTrace(); 
    } 



    Log.d("JSON_SERVER_REQUEST", "SERVER REQUEST aftr task "+jsonResponse); 
1

您的解決方案可能已解決該異常,但您仍然需要等待,並且用戶可能注意到該應用程序未響應。如果請求超過5秒,Android將只顯示「應用不響應」提醒。

這裏是一個解決方案時,您需要從的AsyncTask找回數據,你可以使用:

使用的接口:

public interface INeedDataBack { 
    public void dataIsReady(String data); 
} 

實現你的活動,接口:

... Activity implements INeedDataBack { 
    ... 
    public void dataIsReady(String response) { 
     Log.d("JSON_SERVER_REQUEST", response); 
    } 
... 
} 

調整任務如下: 而不是 Context context;使用INeedDataBack context;

並在您的onPostExecute(INeedDataBack)context.dataIsReady(result);將數據傳遞給您的活動。

就是這樣。

+0

雅我已經做到了這一點,但忘了發佈這個與我的答案! –