【问题标题】:How can I wait for the callback? [closed]如何等待回调? [关闭]
【发布时间】:2017-02-02 21:51:35
【问题描述】:

我想在循环中调用我的 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 试过了,但是不行。

【问题讨论】:

  • 首先,向我们展示一些您尝试过的代码。其次,尝试使用Handler.post(),并将间隔设置为Handler,以进行重复调用。是android.os.Handler
  • 我编辑了这个问题,很抱歉一开始没有代码。

标签: android loops asynchronous android-asynctask callback


【解决方案1】:

始终从您提到的回调中调用下一个调用。跟踪您在 URL 数组中的位置。

类似这样的东西(代码未经测试!)

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
   }

};

【讨论】:

  • 我添加了一些代码,你能再检查一下吗?
  • 所以你的意思是,我应该为此创建一个方法并始终使用另一个 URL 调用它自己?
  • 哦,我的 fckn ohohoho ooooooooh 它有效。我不敢相信哈哈。非常感谢:D。我太笨了,我为此工作了 2 天:DD
  • 路德维希竞选总统
【解决方案2】:

这可能会有所帮助:

在你的异步任务中添加:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);

在 preExecute() 方法中:

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

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

dialog.dismiss();

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 2016-09-03
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多