【问题标题】:Retrofit 2 return response data object for further useRetrofit 2 返回响应数据对象以供进一步使用
【发布时间】:2016-09-12 16:13:08
【问题描述】:

我在 Android 中使用 POJO 和 Retrofit2 来调用 REST 服务来获取一些数据。我确实收到了 response.body() 中的数据,但我不希望将这些数据分配给任何 android UI 组件。我想获取这个返回的对象并返回或在 onResponse 之外工作。

对不起,我是 JAVA 或回调的新手,但在搜索时发现我需要编写回调但不知道如何编写。有人可以帮忙吗。

代码如下:

public String getUserIPCountry(Context context){       

    ipf = new Ipinfo();

    IpinfoAPI.Factory.getInstance().getCountryCode().enqueue(new Callback<Ipinfo>() {
        @Override
        public void onResponse(Call<Ipinfo> call, Response<Ipinfo> response) {

            if(response.isSuccessful()){

               //Want to return/use below data outside of this method
               //response.body().getCountryCode();
            }
        }

        @Override
        public void onFailure(Call<Ipinfo> call, Throwable t) {

        }
    });

    return null;
}    

【问题讨论】:

    标签: java android retrofit pojo retrofit2


    【解决方案1】:

    在操作getUserIPCountry 中设置Callback,当数据从服务器到达时将被调用。 执行不会停止并等待响应。 如果服务器响应正常,将调用onResponse,如果出现问题,将调用onFailure

    因此,在CallbackonResponse 方法中,您应该通知感兴趣的类数据到达(例如,显示数据的ui 类)。

    【讨论】:

    • 谢谢巴勃罗。我只能将数据设置为 UI 元素或在 onresponce 中工作。我想要的是 - 我有一个对象 public Ipinfo xyz,它是在 ipinfo 类型的 oncreate 方法中创建和分配的。因此,xyz 的一部分在 getUserIPCountry 方法之外被赋值,并且只想在 onresponse 中使用 xyz.setip() 来分配 IP 字段。
    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2015-03-31
    • 2017-06-14
    • 2017-02-06
    相关资源
    最近更新 更多