0

从主活动调用 AsyncTask 时出现异常

下面的函数我在 jsonResponse 变量中调用名为“serverConnectorTask”的 AsyncTask 类,我需要获取从 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)
4

6 回答 6

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);数据传递给您的活动。

应该是这样的。

于 2013-09-25T16:05:27.563 回答
0

I solved this issue by serverConnectorTask.execute(jsonRequest).get() which will make the process to wait ie Waits if necessary for the computation to complete, and then retrieves its result.

    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 );
于 2013-09-25T12:52:04.547 回答
0

在方法中CreateJsonConnectNParseResponse

更改此行

Log.d("JSON_SERVER_REQUEST", jsonResponse);

变成这样

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

我想这只修复了您当前拥有的 NullPointerException,您可能会遇到更多问题。让我们一一修复它们。

于 2013-09-25T10:41:03.303 回答
0

根据此处的文档,

您需要将字符串参数传递给 log.d 方法。可能,变量 jsonResponse 为空。确保在传递 log.d 方法之前将 json 响应转换为字符串

于 2013-09-25T10:52:58.917 回答
0

此行可能会给您错误Log.d("JSON_SERVER_REQUEST", jsonResponse);,因为您正在尝试使用 NULL 值打印日志。尝试初始化变量。例如:String jsonResponse="";

于 2013-09-25T10:53:27.917 回答
0

使用这样的线程:

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

                    }
                    }.start();
于 2013-09-25T10:40:23.317 回答