从onResponse回调中获取数据并以相同的方法返回

时间:2016-09-29 11:11:56

标签: android callback retrofit

这是我的代码。

-office 365

而且我真的不知道如何简单地返回保存在时间戳变量中的响应。有任何想法吗?提前致谢。

3 个答案:

答案 0 :(得分:2)

如果要同步调用此方法,可以使用以下代码

private long getLastTimestamp() {

        retrofit2.Call<UserStatistic> call = api.getUserStatistics();

        UserStatistic statistics = call.execute().body();

        long timestamp = statistics.YOUR_CODE;

        return timestamp;
    }

或者如果你想进行异步调用,那就像这样调用这个方法

private void callingMethod () {

        getLastTimestamp (new Callback<UserStatistic>() {

            @Override
            public void onResponse(retrofit2.Call<UserStatistic> call, Response<UserStatistic> response) {
                if (response.body() != null)
                {
                    List<Statistic> statistics = response.body().getData();

                    statistics.get(statistics.size() - 1).Data;
                }
            }

            @Override
            public void onFailure(retrofit2.Call<UserStatistic> call, Throwable t) {
                Log.d("LOG", "Something went wrong :c");
            }

        });
    }

    private long getLastTimestamp(Callback<UserStatistic> callback)
    {
        long timestamp = 0;
        retrofit2.Call<UserStatistic> call = api.getUserStatistics();

        call.enqueue(callback);

        return timestamp;
    }

答案 1 :(得分:0)

这是因为

<script type="text/JavaScript">
document.observe("dom:loaded", function() {
addWellListeners();
// Make sure we have no drag selection
$$(".plate").each(removeDragSelection);
Ajax.Responders.register({
  onComplete: function() {
$$(".plate").each(removeDragSelection);
  }
});

// Add right click context menu stuff
Event.observe(document, "contextmenu", function(event) {
// Only display context menu if inside the well area
if (Event.findElement(event, 'div').hasClassName('well')) {
 event.stop();
 showContextMenu(event.pointerX(), event.pointerY());
}
});
});
</script>
<% end %>





<% content_for :contextmenu do %>
<div id="context_menu" class="context_menu" style="display: none;">
<a href="#" onclick="addSelected(); return false;">Add</a><br />
<hr></hr>
<a href="#" onclick="editSelected(); return false;">Replace</a><br />
<hr></hr>
<a href="#" onclick="deleteSelected(); return false;">Delete</a><br />
</div>
<div id="context_menu_dis" class="context_menu" style="display: none;">
<span class="disabled">Add</span><br />
<hr></hr>
<span class="disabled">Replace</span><br />
<hr></hr>
<a href="#" onclick="deleteSelected(); return false;">Delete</a><br />
</div>
<% end %>

这一行

retrofit2.Call<UserStatistic> call = api.getUserStatistics();

将创建一个监听器,当在此监听器的helop内网络调用后加载数据时,将调用onResponse()方法

答案 2 :(得分:0)

通过调用call.enqueue(...)方法,网络操作在单独的线程上执行。

如果要在方法中返回结果,则必须使用call.execute()方法同步执行网络操作。

但请小心,因为您无法在UI线程(https://developer.android.com/training/basics/network-ops/connecting.html)上执行网络操作。

希望有所帮助!