如何在递归时获取对象的引用?

时间:2013-11-27 04:29:30

标签: android recursion

我从活动开始asynctask。有时SearchAdd不会返回所需的结果(由于TimeOuts等)因此,我将其称为recursivly最多5次。但我搞砸了,如何在自我调用后更新活动中的SearchAdd。

SearchAdd s = new SearchAdd(callback);
                s.execute();

Asyntask

    public class SearchAdd extends AsyncTask<Void, Void, JSONObject> {

        private SearchAddInterface callback;
        private int trial = 0;

        public SearchAdd(SearchAddInterface callback) {
            this.callback = callback;
        }

        public SearchAdd(SearchAddInterface callback, int trial) {
            this.callback = callback;
            this.trial = trial;
        }

        @Override
        protected JSONObject doInBackground(Void... arg0) {
            return JSONParser.getJSONfromURL(RequestStringCreater
                    .concatenationStrings().replaceAll("\\s", "%20"));
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            if (result == null){
                if(trial <5){
                SearchAdd sAdd = new SearchAdd(callback, trial);}
}

        }else{
            // do job
            }

        }

1 个答案:

答案 0 :(得分:0)

要删除递归并允许取消请求,您可以执行以下操作:

public class SearchAdd extends AsyncTask<Void, Void, JSONObject> {

    private SearchAddInterface callback;
    private int trial = 0;
    private boolean cancel = false;

    public SearchAdd(SearchAddInterface callback) {
        this.callback = callback;
    }

    public void cancel() {
        cancel = true;
    }

    @Override
    protected JSONObject doInBackground(Void... arg0) {
        JSONObject result = null;
        while (!cancel && (trial < 5) && (result == null)) {
            trial++;
            result = JSONParser.getJSONfromURL(RequestStringCreater.concatenationStrings().replaceAll("\\s", "%20"));
        }
        return result;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);
        if (cancel) {
            // The request was cancelled
        } else if (result == null) {
            // All trials have failed.
        } else {
            // Do job
        }
    }
}