从Main活动调用AsyncTask时获取异常

时间:2013-09-25 10:26:30

标签: java android android-asynctask

从主要活动

调用AsyncTask时出现异常

在函数下面,我调用名为“serverConnectorTask”类的AsyncTask 在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)

6 个答案:

答案 0 :(得分: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);将数据传递给您的活动。

那应该是它。

答案 1 :(得分:0)

使用这样的线程:

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

                    }
                    }.start();

答案 2 :(得分:0)

方法CreateJsonConnectNParseResponse

更改此行

Log.d("JSON_SERVER_REQUEST", jsonResponse);

就像这样

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

我认为这只会修复您当前拥有的NullPointerException,并且您可能会遇到更多问题。让我们一个一个地解决它们。

答案 3 :(得分:0)

根据文件here

您需要将字符串参数传递给log.d方法。可能,变量jsonResponse为null。 确保在传递log.d方法

之前将json响应转换为字符串

答案 4 :(得分:0)

这一行可能会给你错误Log.d("JSON_SERVER_REQUEST", jsonResponse);因为你试图用NULL值打印日志。试着初始化变量。 例如:String jsonResponse="";

答案 5 :(得分: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 );