从AsyncTask类返回数据

如何从AsyncTask获取数据? 我的MainActivity正在调用触发AsyncTask的DataCall.getJSON函数,但我不确定如何将数据恢复到原始Activity。

调用DataCall的MainActivity应该返回一个字符串并将其保存在state_data

 String state_data = DataCall.getJSON(spinnerURL,spinnerContentType); 

DataCall:

 public class DataCall extends Activity { private static final String TAG = "MyApp"; private class DownloadWebPageTask extends AsyncTask { protected String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } protected void onPostExecute(String result) { //THIS IS WHERE I NEED TO RETURN MY DATA TO THE MAIN ACTIVITY. (I am guessing) } } public void getJSON(String myUrlString, String contentType) { DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://www.mywebsite.com/" + myUrlString }); } } 

对我来说,关键是创建一个名为URLWithParams的类,因为AsyncTask只允许1个types的IN发送,我需要HTTP请求的URL和params。

 public class URLWithParams { public String url; public List nameValuePairs; public URLWithParams() { nameValuePairs = new ArrayList(); } } 

然后我将它发送给JSONClient:

 public class JSONClient extends AsyncTask { private final static String TAG = "JSONClient"; ProgressDialog progressDialog ; GetJSONListener getJSONListener; public JSONClient(GetJSONListener listener){ this.getJSONListener = listener; } @Override protected String doInBackground(URLWithParams... urls) { return connect(urls[0].url, urls[0].nameValuePairs); } public static String connect(String url, List pairs) { HttpClient httpclient = new DefaultHttpClient(); if(url == null) { Log.d(TAG, "want to connect, but url is null"); } else { Log.d(TAG, "starting connect with url " + url); } if(pairs == null) { Log.d(TAG, "want to connect, though pairs is null"); } else { Log.d(TAG, "starting connect with this many pairs: " + pairs.size()); for(NameValuePair dog : pairs) { Log.d(TAG, "example: " + dog.toString()); } } // Execute the request HttpResponse response; try { // Prepare a request object HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); response = httpclient.execute(httpPost); // Examine the response status Log.i(TAG,response.getStatusLine().toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); return json; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(String json ) { getJSONListener.onRemoteCallComplete(json); } public interface GetJSONListener { public void onRemoteCallComplete(String jsonFromNet); } } 

然后像我这样从我的主类中调用它

 public class BookCatalog implements GetJSONListener { private final String TAG = this.getClass().getSimpleName(); private String catalog_url = "URL"; private void getCatalogFromServer() { URLWithParams mURLWithParams = new URLWithParams(); mURLWithParams.url = catalog_url; try { JSONClient asyncPoster = new JSONClient(this); asyncPoster.execute(mURLWithParams); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onRemoteCallComplete(String jsonBookCatalogList) { Log.d(TAG, "received json catalog:"); Log.d(TAG, jsonBookCatalogList); JSONObject bookCatalogResult; try { bookCatalogResult = (JSONObject) new JSONTokener(jsonBookCatalogList).nextValue(); JSONArray books = bookCatalogResult.getJSONArray("books"); if(books != null) { ArrayList newBookOrdering = new ArrayList(); int num_books = books.length(); BookCatalogEntry temp; DebugLog.d(TAG, "apparently we found " + Integer.toString(num_books) + " books."); for(int book_id = 0; book_id < num_books; book_id++) { JSONObject book = books.getJSONObject(book_id); String title = book.getString("title"); int version = book.getInt("price"); } } } catch (JSONException e) { e.printStackTrace(); } } } 

修改你的AsyncTask如下:

 public class GetData extends AsyncTask { DataDownloadListener dataDownloadListener; public GetData() { //Constructor may be parametric } public void setDataDownloadListener(DataDownloadListener dataDownloadListener) { this.dataDownloadListener = dataDownloadListener; } @Override protected Object doInBackground(Object... param) { // do your task... return null; } @Override protected void onPostExecute(Object results) { if(results != null) { dataDownloadListener.dataDownloadedSuccessfully(results); } else dataDownloadListener.dataDownloadFailed(); } public static interface DataDownloadListener { void dataDownloadedSuccessfully(Object data); void dataDownloadFailed(); } } 

并在您的活动中使用它

 GetData getdata = new GetData(); getdata.setDataDownloadListener(new DataDownloadListener() { @SuppressWarnings("unchecked") @Override public void dataDownloadedSuccessfully(Object data) { // handler result } @Override public void dataDownloadFailed() { // handler failure (eg network not available etc.) } }); getdata.execute(""); 

注意 :对于正在阅读此内容的人。

请考虑这篇文章,以获得最佳和可能正确的实施。

虽然我不同意为这个简单的任务创建一个新的活动

 startActivityForResult() 

从另一个活动获取数据。

检查一下 。 您可以将数据存储到Intent的附加内容中。 但是如果您有大量数据,最好将其写入文件,从另一个完成下载的活动中获取结果,然后读取文件。

序列化然后读取它。 我知道的唯一方法。

一些选择:

a)使你的bean实现Serializable接口,然后你可以通过Intent传递你的bean。

b)实现Application接口(需要在manifest中创建一个条目),在Application类中使用setter \ getter方法。 您可以在AsyncTask中的Application中设置bean,然后从Activity中检索。

很抱歉这么晚回答,我想到这个时候你可能已经解决了这个问题。 当我在寻找别的东西时,我遇到了你的问题。 我在这里粘贴一个链接,可能对其他人有所帮助。