我怎么能等待回调?

时间:2016-09-25 14:15:58

标签: android loops asynchronous android-asynctask callback

我想在循环中调用我的JSON类,总是使用另一个URL,并始终将结果传递给RecyclerView。问题是我无法将此方法放入循环中,因为循环不会等待回调...任何想法如何做到这一点?

final JSON json = new JSON("http://1956.osaarchivum.org/api/items?collection=13&page=" + page + "&per_page=10", SzabadEuMusorokViewActivity.this);
    json.mJSONInterface = new JSONInterface() {
        @Override
        public void startActivityJSON() {
            mAdapter.add((ArrayList<Collection>) json.getCollections());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                }
            });
        }};

我希望在呼叫完成后始终增加页面变量。我用lopp尝试了它但它不起作用。

2 个答案:

答案 0 :(得分:0)

始终从您提及的回调中调用下一个调用。跟踪您的网址数组中的位置。

像这样的事情(代码未经测试!)

class JsonFetcher {
   int _start, _end, _current;
   public JsonFetcher(int start, int end) {
      _start=start;_end=end;_current=start-1;
      fetch_next()
   }
   public void fetch_next() {
     _current += 1;
     if (_current < end)
        // Trigger your JSON fetch here and have it call fetch_next in the callback
   }

};

答案 1 :(得分:0)

这可能会有所帮助:

你的asynctask中的

添加:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);
在preExecute()方法中

this.dialog.setMessage("Processing..."); 
this.dialog.show();

在onPostExecute(Void result)方法中添加:

dialog.dismiss();