有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从异步任务返回对象时出现java问题

我有一个扩展AsyncTask的类(RestClient.java): 包裹组织。stocktwits。助手

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 安卓.os.AsyncTask;
import 安卓.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为null,因为它是在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);}

共 (2) 个答案

  1. # 1 楼答案

    我被doInBackground在onPostExecute中消耗的结果弄错了

    doInBackground(参数…),援引 立即打开背景线程 在PreExecute()完成后 执行。此步骤用于 执行背景计算 可能需要很长时间。参数 异步任务的 到这一步测试结果 计算必须由该 步骤,并将传递回 最后一步。这一步也可以使用 出版进度(进度…)到 发布一个或多个单位的 进步这些值已发布 在UI线程上,在 onProgressUpdate(进度…)迈步

    @Override
    
    protected void onPostExecute(JSONObject json ) {
    // DO stuff here ( it's UI thread )
     mJsonFromTheActivity = json;
    }
    
  2. # 2 楼答案

    嘿,你可以使用侦听器来解决这个问题。 为了使用这个,我稍微修改了代码

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