I\'m trying to create a class to retrieve a JsonArray from a url. This class extends AsyncTask to avoid creating multiple AsyncTasks on interfaces.
The class works fin
You need to use a callback. Simply add the following…
variable:
private Callback callback;
inner-interface:
public interface Callback{
public void call(JSONArray array);
}
constructor:
public QueryJsonArray(Callback callback) {
this.callback = callback;
}
Additionally, change your class declaration to:
public class QueryJsonArray extends AsyncTask
and change the return type of doInBackground
to JSONArray
.
At the end of doInBackground
, add:
return jsonRetorno;
Finally, add the following method with contents:
public void onPostExecute(JSONArray array) {
callback.call(array);
}
Now, to execute the task, just do:
QueryJsonArray obj = new QueryJsonArray(new Callback() {
public void call(JSONArray array) {
//TODO: here you can handle the array
}
});
JSONArray jArray = obj.execute(myUrl);
As a side note, you could greatly simplify all of this using a third party library, such as droidQuery, which would condense all of the above code to:
$.ajax(new AjaxOptions().url(myUrl).success(new Function() {
public void invoke($ d, Object… args) {
JSONArray array = (JSONArray) args[0];
//TODO handle the json array.
}
});