Get back JSON from AsyncTask

So, I have this bootloader class that extends AsyncTask. Then I do new loader().execute();, but I want to use the JSONArray response , which my loader class returns , how to do it? Because I need it in several different places? Or should I just move my code to onPostExecute and do everything from there?

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();
    }
}
+3
source share
1 answer

The method onPostExecutehas as the parameter JSONArrayyou returned from the method doInBackground.

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

onPostExecute " doInBackground. - , doInBackground null, ". ~ API- , , .

+4

All Articles