【问题标题】:Problem returning an object from an AsyncTask从 AsyncTask 返回对象的问题
【发布时间】:2010-09-09 21:31:46
【问题描述】:

我有一个扩展 AsyncTask 的类 (RestClient.java): 包 org.stocktwits.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class RestClient extends AsyncTask<String, Void, JSONObject>{
    public JSONObject jsonObj = null;
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


    /* This is a test function which will connects to a given
     * rest service and prints it's response to Android Log with
     * labels "Praeda".
     */
    public static JSONObject connect(String url)
    {

        HttpClient httpclient = new DefaultHttpClient();


        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i("Praeda",response.getStatusLine().toString());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);

                // A Simple JSONObject Creation
                JSONObject json=new JSONObject(result);

                // Closing the input stream will trigger connection release
                instream.close();

                return json;
            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected JSONObject doInBackground(String... urls) {
        return connect(urls[0]);
    }

    @Override
    protected void onPostExecute(JSONObject json ) {
        this.jsonObj = json;
    }

    public void setJSONObject(JSONObject jsonFromUI){
        this.jsonObj = jsonFromUI;
    }

    public JSONObject getJSONObject(){
        return this.jsonObj;
    }

}

我正在尝试在我的主类 (Main.java) 上执行 AsyncTask:

    RestClient rc = new RestClient();
    JSONObject json = new JSONObject();
    rc.setJSONObject(json);
    rc.execute(buildQuery());
    json = rc.getJSONObject();

//do some stuff with the json object
try { JSONObject query = json.getJSONObject("query");
//...
}

json 为空,因为它在 onPostExecute() 之前被调用。如何获取我的 JSON?

更新: 我需要在 onPostExecute() 中运行这个 try 块:

try {

            JSONObject query = json.getJSONObject("query");
            JSONObject results = query.getJSONObject("results");

            if (query.getString("count").equals("1")) { // YQL JSON doesn't
                // return an array for
                // single quotes
                JSONObject quote = results.getJSONObject("quote");

                Quote myQuote = new Quote();
                myQuote.setName(quote.getString("Name"));
                myQuote.setSymbol(quote.getString("Symbol"));
                myQuote.setLastTradePriceOnly(quote
                        .getString("LastTradePriceOnly"));
                myQuote.setChange(quote.getString("Change"));
                myQuote.setOpen(quote.getString("Open"));
                myQuote.setMarketCapitalization(quote
                        .getString("MarketCapitalization"));
                myQuote.setDaysHigh(quote.getString("DaysHigh"));
                myQuote.setYearHigh(quote.getString("YearHigh"));
                myQuote.setDaysLow(quote.getString("DaysLow"));
                myQuote.setYearLow(quote.getString("YearLow"));
                myQuote.setVolume(quote.getString("Volume"));
                myQuote.setAverageDailyVolume(quote
                        .getString("AverageDailyVolume"));
                myQuote.setPeRatio(quote.getString("PERatio"));
                myQuote.setDividendYield(quote.getString("DividendYield"));
                myQuote.setPercentChange(quote.getString("PercentChange"));

                quotesAdapter.add(myQuote);}

【问题讨论】:

    标签: java android asynchronous android-asynctask


    【解决方案1】:

    嘿,您可以使用侦听器来解决此问题。 我稍微更改了代码以使用它。

    package com.insidetip.uob.data;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;
    
    public class JSONClient extends AsyncTask<String, Void, JSONObject>{
        ProgressDialog progressDialog ;
        GetJSONListener getJSONListener;
        Context curContext;
        public JSONClient(Context context, GetJSONListener listener){
            this.getJSONListener = listener;
            curContext = context;
        }
        private static String convertStreamToString(InputStream is) {
            /*
             * To convert the InputStream to String we use the BufferedReader.readLine()
             * method. We iterate until the BufferedReader return null which means
             * there's no more data to read. Each line will appended to a StringBuilder
             * and returned as String.
             */
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
    
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return sb.toString();
        }
    
    
        public static JSONObject connect(String url)
        {
            HttpClient httpclient = new DefaultHttpClient();
    
            // Prepare a request object
            HttpGet httpget = new HttpGet(url); 
    
            // Execute the request
            HttpResponse response;
            try {
                response = httpclient.execute(httpget);
                // Examine the response status
                Log.i("Praeda",response.getStatusLine().toString());
    
                // Get hold of the response entity
                HttpEntity entity = response.getEntity();
    
                if (entity != null) {
    
                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();
                    String result= convertStreamToString(instream);
    
                    // A Simple JSONObject Creation
                    JSONObject json=new JSONObject(result);
    
                    // Closing the input stream will trigger connection release
                    instream.close();
    
                    return json;
                }
    
    
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            return null;
        }
        @Override
        public void onPreExecute() {
            progressDialog = new ProgressDialog(curContext);
            progressDialog.setMessage("Loading..Please wait..");
            progressDialog.setCancelable(false);
            progressDialog.setIndeterminate(true);
            progressDialog.show();
    
        }
    
        @Override
        protected JSONObject doInBackground(String... urls) {
            return connect(urls[0]);
        }
    
        @Override
        protected void onPostExecute(JSONObject json ) {
            getJSONListener.onRemoteCallComplete(json);
            progressDialog.dismiss();
        }
    }
    

    像这样在调用类中使用。

        JSONClient client = new JSONClient(context, listener);
        client.execute(URL);
    

    别忘了实现监听器

    public interface GetJSONListener {
        public void onRemoteCallComplete(JSONObject jsonFromNet);
    }
    

    【讨论】:

    • 不错。我在我的项目中使用它。谢谢。
    【解决方案2】:

    我误会了 doInBackground 的结果可以在 onPostExecute 中使用

    doInBackground(Params...),调用于 立即后台线程 在 PreExecute() 完成之后 执行。此步骤用于 执行后台计算 可能需要很长时间。参数 的异步任务通过 到这一步。 结果 计算必须由此返回 步骤并将被传递回 最后一步。这一步也可以使用 发布进度(进度...)到 发布一个或多个单元 进步。这些值已发布 在 UI 线程上,在 onProgressUpdate(Progress...) 步骤。

    @Override
    
    protected void onPostExecute(JSONObject json ) {
    // DO stuff here ( it's UI thread )
     mJsonFromTheActivity = json;
    }
    

    【讨论】:

    • 所以让我们说 onPostExecute() 返回一个 JSONObject。我怎么能从我的主要课程中调用它?我可以只说 JSONObject json = rc.onPostExecute() 并获取返回的对象吗?
    • 否,但您可以从 onPostExecute 将其分配给成员 var
    • 这可能不是(也可能不是)正确的方法,但我做到这一点的一种方法是声明一个全局变量,然后在 onPostExecute 方法中,将该变量设置为传递的变量进入 onPostExecute。例如私有 JSONObject jsonObject; ...onPostExecute(JSONObject json) { jsonObject = json; }。我也想知道一个更好的方法,但我还没有做太多的搜索。
    • 很好的例子——懒惰的拇指下载对吗?让我找到网址
    • 我们可能可以让它工作,但是为了时间的缘故,将您的任务作为嵌套类移动到活动中,您将可以访问您的适配器以及活动中您需要的任何其他内容。
    【解决方案3】:

    execute() 总是返回 AsyncTask 本身。你从 doInBackground() 返回的对象在 onPostExecute() 中交给你。

    【讨论】:

    • 感谢您的澄清。如何从 onPostExecute() 获取 JSONObject ?
    【解决方案4】:

    如果您将异步任务作为活动的嵌套内部类,则可以将活动变量之一设置为异步任务的结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多