从另一个活动调用AsyncTask

时间:2012-08-20 22:36:51

标签: android android-activity android-asynctask

我需要你的帮助我过去两天一直坚持这个,我试图从另一个活动中调用这个AsyncTask并获取返回的字符串但是在网上阅读了几个帖子之后我就这样了我无法做到这一点。有人可以指出我需要做什么或非常厚颜无耻地发布一些代码并解释它,所以我知道发生了什么。我非常感谢你的帮助!

E.g

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;
        }
    }

1 个答案:

答案 0 :(得分:1)

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

相关问题