传递参数并从android中的asynctask获取输出

时间:2015-02-04 07:35:37

标签: android

我试图传递参数并从asyntask类中获取。这是我的asyntask类

public class GetDataFromAsyncTask extends AsyncTask<String, Integer, Object>{
        @Override
    protected Object doInBackground(String... strurl) {
        // TODO Auto-generated method stub
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet getReq = new HttpGet(strurl[0]);
        ResponseHandler<String> handler = new BasicResponseHandler();

       // HttpResponse response;
        Object responseString = null;
        try {
            //response = httpclient.execute(new HttpGet(strurl[0]));
            HttpResponse execute = httpclient.execute(getReq);
            responseString = httpclient.execute(getReq,handler);           
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
        protected void onPostExecute(Object result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
        }

}

我试图从另一个班级打电话给下面的

String url = "some url";
        //GetAsynTask 
        Object strResult=null;
        strResult = new GetDataFromAsyncTask().execute(url);
        if(strResult!=null)
        {
            JSONArray objAry;
            try {
                String data = (String)strResult;
                objAry = new JSONArray(data);
                 }
        }

但上面的代码不起作用。当调试源找不到错误时。 任何人都可以帮忙... 提前谢谢......

3 个答案:

答案 0 :(得分:0)

您需要实现一个接口类。接口类将允许您创建一个回调函数,您的异步线程将在完成后调用该函数。您可以找到如何执行此操作here

编辑 - 将链接更改为更直接的大纲

1)创建一个新界面。为此,请创建一个包含以下代码的新类:

public interface AsyncResponse {
    void processFinish(Object output);
}

2)将以下内容添加到GetDataFromAsyncTask类:

public class GetDataFromAsyncTask extends AsyncTask{
public AsyncResponse delegate=null; // Creates Instance of your interface

   @Override
   protected void onPostExecute(Object result) {
      delegate.processFinish(result); // Calls processFinish in the interface
   }

3)将以下内容添加到正在调用的任何活动中:

public class MainActivity implements AsyncResponse{ //implement AsyncResponse
   GetDataFromAsyncTask strResult = new GetDataFromAsyncTask.execute(url);
    @Override
    public void onCreate(Bundle savedInstanceState) {
     strResult.delegate = this;
    }

//This method will run once the thread returns
   void processFinish(Object output){
    if(strResult!=null)
    {
        JSONArray objAry;
        try {
            String data = (String)strResult;
            objAry = new JSONArray(data);
             }
    }
   }
}

希望这会有所帮助,祝你好运。

答案 1 :(得分:0)

您有两种选择:

  1. 更容易的是两个使AsyncTask类成为调用AsyncTask的类的内部类。然后,您只需在AsyncTask类的strResult方法中设置onPostExecute()变量的值。
  2. 如果要将AsyncTask类保持为单独的顶级类,则应遵循Matty建议的方法。向AsyncTask类添加一个接口,让你的调用类实现这个接口,这样一旦任务完成就可以得到AsyncTask的结果

答案 2 :(得分:0)

将此Async类放在您的activity类中,您将获得onPostExecute(String result)方法的数据。另外,请确保在清单文件中添加了Internet权限。

class GetDataFromAsyncTask extends AsyncTask<String, Integer, String>{
        @Override
    protected Object doInBackground(String... strurl) {
       String resutString = "";
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();        
        HttpGet getReq = new HttpGet(strurl[0]);
      HttpResponse response = client.execute(getReq);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) {
                HttpEntity entityResponse = response.getEntity();
                InputStream content = entityResponse.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    builder.append(line + "\n");
                }
                reader.close();
                resutString = builder.toString();
                Log.d(TAG, "Successfuly :" + resutString);
            } else {
                Log.d(TAG, "Error seding data");
            }
        } catch (ConnectTimeoutException e) {
            Log.w("Connection Tome Out", e);
        } catch (ClientProtocolException e) {
            Log.w("ClientProtocolException", e);
        } catch (SocketException e) {
            Log.w("SocketException", e);
        } catch (IOException e) {
            Log.w("IOException", e);
        } /*catch (JSONException e) {
            e.printStackTrace();
        }*/
        return resutString;
    }

    @Override
        protected void onPostExecute(String result) {            
            super.onPostExecute(result);
            strResult = result;
            if(strResult!=null)
            {
                  JSONArray objAry;
                  try {
                  String data = (String)strResult;
                  objAry = new JSONArray(data);
                  }catch(JSONException e){}

             }
        }

}

像这样调用此代码

new GetDataFromAsyncTask().execute(url)