从 AsyncTask 类返回数据 [英] Return data from AsyncTask class

查看:31
本文介绍了从 AsyncTask 类返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I get the data from my AsyncTask? My MainActivity is calling the DataCall.getJSON function that triggers the AsyncTask but I am not sure how to get the data back to the original Activity.

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

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

数据调用:

public class DataCall extends Activity {
    private static final String TAG = "MyApp";


    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {


        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 个类型,我需要 URL 和HTTP 请求的参数.

The key for me was to create a class called URLWithParams or something because AsyncTask will allow only 1 type to be sent IN, and I needed both the URL and the params for the HTTP request.

public class URLWithParams {

    public String url;
    public List<NameValuePair> nameValuePairs;

    public URLWithParams()
    {
        nameValuePairs = new ArrayList<NameValuePair>();
    }
}

然后我将它发送到 JSONClient:

and then I send it to a JSONClient:

public class JSONClient extends AsyncTask<URLWithParams, Void, String> {
    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<NameValuePair> 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);
    }

}

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

Then call it from my main class like this

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<String> newBookOrdering = new ArrayList<String>();
            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 类返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆