【发布时间】:2019-05-21 08:20:31
【问题描述】:
我正在尝试通过回调从 onResponse 方法中获取我解析的数据。这是我的 ApiClient:
public class ApiClient implements Callback<Map<String, Channel>> {
private ChannelCallback listener;
static final String BASE_URL = "https://www.radyoodtu.com.tr/";
public void start(ChannelCallback listener) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestInterface restInterface = retrofit.create(RestInterface.class);
Call<Map<String, Channel>> call = restInterface.getChannels();
call.enqueue(this);
}
@Override
public void onResponse(retrofit2.Call<Map<String, Channel>> call, Response<Map<String, Channel>> response) {
System.out.println(response.code());
if(response.isSuccessful()) {
Map<String, Channel> body = response.body();
listener.setChannels(body);
List<Channel> channels = new ArrayList<>(body.values());
for (Channel channel : body.values()) {
System.out.println(channel.getSong());
}
}
}
@Override
public void onFailure(retrofit2.Call<Map<String, Channel>> call, Throwable t) {
//TODO
}
}
这是我要获取数据的类:
public class Radio implements ChannelCallback {
private ApiClient apiClient = new ApiClient();
public Radio(){
apiClient.start(this);
}
@Override
public void setChannels(Map<String, Channel> body) {
this.apiClient.onResponse(body); // NOT WORKING
}
}
这是我的界面:
public interface ChannelCallback {
void setChannels(Map<String, Channel> body);
}
我需要做的是获取我现在正在使用的 Radio 类的 onResponse 正文数据。在 Radio 类中,我必须使用我需要的数据创建一个频道对象列表,但我什至无法获取数据,因此我什至无法创建该列表。我根本不知道如何操作来自侦听器的数据,也不知道如何访问我在 Radio 类的 ApiClient 中使用的那个侦听器。
【问题讨论】:
标签: java android retrofit2 asynccallback