How to get JsonArray from a class who AsyncTask

后端 未结 1 725
感动是毒
感动是毒 2021-01-25 09:13

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

1条回答
  •  醉话见心
    2021-01-25 09:59

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

    0 讨论(0)
提交回复
热议问题