0

我需要你的帮助在过去的两天里我一直坚持这个问题,我试图从另一个活动中调用这个 AsyncTask 并获取返回的字符串,但是在阅读了网上和 SO 上的几篇文章之后,我无法做。有人可以指出我需要做什么,或者非常厚颜无耻地发布一些代码并解释它,以便我知道发生了什么。我真的很感激帮助!

例如

String jsonString = //returned string from AsyncTask 



public class processJSON extends AsyncTask<Object, Void, String>{

        private Context context;

        public processJSON (Context context){
            this.context = context;
        }

        @Override
        protected String doInBackground(Object... params) {

            int location_id = (Integer) params[0];
            String url = (String) params[1];

            InputStream in = null;
            String result = "";
            JSONObject jArray = null;
            String newURL = url + "?location_id=" + location_id;

            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); 
            HttpResponse response;
            JSONObject json = new JSONObject();
            try{

                HttpPost post = new HttpPost(newURL);
                //json.put("location_id", location_id);
                StringEntity se = new StringEntity(json.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                if (response != null) {
                    in = response.getEntity().getContent(); 
                }
            }catch (Exception e) {
                Log.e("Send JSON", "ERROR: " + e);
                e.printStackTrace();
            }

            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                in.close();
                result = sb.toString();
            }catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            return result;
        }
    }
4

1 回答 1

1

当您实例化它时,您AsyncTask应该接受一个回调作为参数。然后,一旦它运行并完成,您就可以返回通过回调生成的任何值。

于 2012-08-20T22:38:31.787 回答