So I have this loader class which extends AsyncTask. Then I do new loader().execute(); but I want to use the JSONArray response which my loader class returns how do I do that? 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();
}
}
The method
onPostExecutehas as parameter theJSONArrayyou returned from thedoInBackgroundmethod.onPostExecuteruns on your main (caller) activity’s thread, so besides dismissing the dialog in that method, you can process theresultarray further, pass it safely to other methods, etc:the
handler:Some other method:
Since
onPostExecute“Runs on the UI thread after doInBackground. The specified result is the value returned by doInBackground or null if the task was cancelled or an exception occured.” ~API DocsYou can call any method you’ve declared in your class, and pass this array as a parameter to it.