从AsyncTask获取返回的JSON数据

3

我有一个继承自AsyncTask的加载器类。然后我执行 new loader().execute();,但我想使用我的加载器类返回的JSONArray响应,该怎么做?因为我需要在几个不同的地方使用它?或者我应该将我的代码移到onPostExecute并从那里完成所有操作吗?

public class loader extends AsyncTask<String, Integer, JSONArray> {

    ProgressDialog dialog;

    protected void onPreExecute() {

        dialog = ProgressDialog.show(ChallengeList.this, "", "Laddar...");
        dialog.setCancelable(true);
    }

    @Override
    protected JSONArray doInBackground(String... params) {


    JSONArray response = null;
    HttpClient client = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(listURL);

    try {

        HttpResponse resp = client.execute(httppost);
        StatusLine statusLine = resp.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        Log.i("Statuscode", "statusCode"+statusCode);
        if (statusCode == 200) {
            final JSONObject json = new JSONObject();

            json.put("userID", prefs.id());

            response = SendHttp.parseHttp(listURL, json);

        }
    } catch (JSONException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } 

        return response;
    }
    protected void onPostExecute(JSONArray result) {
        dialog.dismiss();
    }
}
2个回答

4

方法onPostExecute的参数是从doInBackground方法返回的JSONArray

onPostExecute在您的主(调用者)活动线程上运行,因此除了在该方法中取消对话框之外,您还可以进一步处理result数组,将其安全地传递给其他方法等:

@Override
protected void onPostExecute(JSONArray result)
{
    super.onPostExecute(result);
    final Message msg = new Message();
    msg.obj = result;
    if (youWantToUseHandler)
        handler.dispatchMessage(msg);
    else
        writeJSONArray(result);
}
处理程序 (handler):
final Handler handler = new Handler()
{
    public void handleMessage(Message msg) 
    {
        final JSONArray result = (JSONArray)msg.obj;
        writeJSONArray(result);
    };
};

一些其他的方法:

private void writeJSONArray(final JSONArray result)
{
    for (int i = 0; i < result.length(); i++)
    {
        try
        {
            Log.d("SAMPLE", result.get(i).toString());
        }
        catch (JSONException e)
        {
            Log.e("SAMPLE", "error getting result " + i, e);
        }
    }
}

onPostExecutedoInBackground之后运行于UI线程。其指定的结果是doInBackground返回的值,如果任务被取消或出现异常,则返回null。 ~API文档 您可以调用在您的类中声明的任何方法,并将此数组作为参数传递给它。


但是有没有办法在 onPostExecute 之外使用它?比如在执行 new loader().execute() 后获取 JSONArray,然后在我的主代码中使用它? - simtaxman
你可以将其传递给处理程序,并从那里使用。在你的主要应用程序中声明一个Handler,在onPostExecute中调用它。 - rekaszeru

0

在下载网页内容后,您可以在onPostExecute方法中使用以下代码:

protected void onPostExecute(String s) { super.onPostExecute(s);

        try {
            JSONObject jsonObject = new JSONObject(s);

            String weatherInfo = jsonObject.getString("weather");

            Log.i("Weather content", weatherInfo);

            JSONArray arr = new JSONArray(weatherInfo);

            for (int i=0; i < arr.length(); i++) {
                JSONObject jsonPart = arr.getJSONObject(i);

                Log.i("main",jsonPart.getString("main"));
                Log.i("description",jsonPart.getString("description"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接