问题从AsyncTask的返回一个对象对象、问题、AsyncTask

2023-09-05 10:35:51 作者:荒唐°

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

 进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;

进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;

进口android.os.AsyncTask;
进口android.util.Log;

公共类RestClient扩展的AsyncTask<字符串,无效的JSONObject> {
    公众的JSONObject jsonObj = NULL;
    私有静态字符串convertStreamToString(InputStream的是){
        / *
         *要InputStream中转换为字符串,我们使用使用BufferedReader.readLine()
         * 方法。我们迭代直到BufferedReader中返回NULL,这意味着
         *没有更多的数据读取。每个行会附加到一个StringBuilder
         *和返回的字符串。
         * /
        的BufferedReader读卡器=新的BufferedReader(新InputStreamReader的(是));
        StringBuilder的SB =新的StringBuilder();

        串线= NULL;
        尝试 {
            而((行= reader.readLine())!= NULL){
                sb.append(行+\ N);
            }
        }赶上(IOException异常E){
            e.printStackTrace();
        } 最后 {
            尝试 {
                is.close();
            }赶上(IOException异常E){
                e.printStackTrace();
            }
        }

        返回sb.toString();
    }


    / *这是一个测试功能,这将连接到一个给定的
     *休息服务,并打印的响应到Android日志,
     *标签Praeda。
     * /
    公共静态的JSONObject连接(字符串URL)
    {

        HttpClient的HttpClient的=新DefaultHttpClient();


        // prepare请求对象
        HTTPGET HTTPGET =新HTTPGET(URL);

        //执行请求
        HTT presponse响应;
        尝试 {
            响应= httpclient.execute(HTTPGET);
            //检查响应状态
            Log.i(Praeda,response.getStatusLine()的toString());

            //弄个响应实体
            HttpEntity实体= response.getEntity();

            如果(实体!= NULL){

                //一个简单的JSON响应读取
                InputStream的河道= entity.getContent();
                字符串结果= convertStreamToString(河道);

                //一个简单的JSONObject创作
                JSONObject的JSON =新的JSONObject的(结果);

                //关闭输入流会触发连接释放
                instream.close();

                返回JSON;
            }


        }赶上(ClientProtocolException E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }赶上(JSONException E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }

        返回null;
    }

    @覆盖
    受保护的JSONObject doInBackground(字符串...网址){
        返回连接(网址[0]);
    }

    @覆盖
    保护无效onPostExecute(JSONObject的JSON){
        this.jsonObj = json的;
    }

    公共无效setJSONObject(JSONObject的jsonFromUI){
        this.jsonObj = jsonFromUI;
    }

    公众的JSONObject getJSONObject(){
        返回this.jsonObj;
    }

}
 

我想执行的AsyncTask在我的主类(Main.java):

  RestClient RC =新RestClient();
    JSONObject的JSON =新的JSONObject();
    rc.setJSONObject(JSON);
    rc.execute(BuildQuery对于());
    JSON = rc.getJSONObject();

//做一些东西与JSON对象
尝试{JSONObject的查询= json.getJSONObject(查询);
// ...
}
 

JSON是空,因为它是onPostExecute前称为()。我怎样才能让我的JSON?

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

 尝试{

            JSONObject的查询= json.getJSONObject(查询);
            JSONObject的结果= query.getJSONObject(结果);

            如果(query.getString(伯爵)。等于(1)){// YQL JSON不
                //返回一个数组
                //单引号
                JSONObject的报价= results.getJSONObject(报价);

                报价myQuote =新报价();
                myQuote.setName(quote.getString(名称));
                myQuote.setSymbol(quote.getString(符号));
                myQuote.setLastTradePriceOnly(报价
                        .getString(LastTradePriceOnly));
                myQuote.setChange(quote.getString(更改));
                myQuote.setOpen(quote.getString(打开));
                myQuote.setMarketCapitalization(报价
                        .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(卷));
                myQuote.setAverageDailyVolume(报价
                        .getString(AverageDailyVolume));
                myQuote.setPeRatio(quote.getString(操作));
                myQuote.setDividendYield(quote.getString(DividendYield));
                myQuote.setPercentChange(quote.getString(PercentChange));

                quotesAdapter.add(myQuote);}
 
Android 网络和服务 AsyncTask

解决方案

我被doInBackground的结果可以onPostExecute食用被误认为

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

  @覆盖

保护无效onPostExecute(JSONObject的JSON){
//这里做的东西(它的UI线程)
 mJsonFromTheActivity = json的;
}
 

I have a class (RestClient.java) that extends AsyncTask: package 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;
    }

}

I am trying to execute the AsyncTask on my Main class (Main.java):

    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 is null because it is called before onPostExecute(). How can I get my JSON?

UPDATE: I need to run this try block in onPostExecute():

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

解决方案

I'm be mistaken by result of doInBackground can be consumed in onPostExecute

doInBackground(Params...), invoked on the background thread immediately after on PreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

@Override

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