我正在尝试通过Retrofit获得API调用的对象列表,但我只是找不到这样做的方法:(这是我构建的功能:
private List<Business> businesses getBusinesses()
{
List<Business> businessesList = new ArrayList<>();
Call<List<Business>> call = jsonPlaceHolderApi.getBusinesses();
call.enqueue(new Callback<List<Business>>() {
@Override
public void onResponse(Call<List<Business>> call, Response<List<Business>> response) {
if(!response.isSuccessful())
{
textViewResult.setText("Code: " + response.code());
return;
}
List<Business> businesses = response.body();
for(Business business : businesses)
{
String content = "";
content += "ID: " + business.getId() + "n";
content += "Name: " + business.getName() + "n";
content += "On promotion: " + business.isOnPromotion() + "nn";
textViewResult.append(content);
}
businessesList = businesses;
}
@Override
public void onFailure(Call<List<Business>> call, Throwable t) {
call.cancel();
textViewResult.setText(t.getMessage());
}
});
}
我正在尝试获得企业的响应并将其返回。谁能帮我?感到沮丧:(
使用 call.enqueue
执行改造调用的方式是异步的。这种方法没有错。实际上,这也许是最好的选择,因为网络呼叫可能需要一段时间,而您不想不必要地阻止。
不幸的是,这意味着您无法从功能中返回结果。在大多数情况下,如果您这样做了,返回后可能会完成电话,从而使您的返回无用。
有几种处理方法,最简单的方法是使用回调。例如:
interface OnBusinessListReceivedCallback {
void onBusinessListReceived(List<Business> list);
}
private void businesses getBusinesses(OnBusinessListReceivedCallback callback){
Call<List<Business>> call = jsonPlaceHolderApi.getBusinesses();
call.enqueue(new Callback<List<Business>>() {
@Override
public void onResponse(Call<List<Business>> call, Response<List<Business>> response) {
if(!response.isSuccessful()){
textViewResult.setText("Code: " + response.code());
return;
}
callback.onBusinessListReceived(response.body());
}
@Override
public void onFailure(Call<List<Business>> call, Throwable t) {
call.cancel();
textViewResult.setText(t.getMessage());
}
});
}
您可以这样称呼:
getBusinesses(new OnBusinessListReceivedCallback() {
public void onBusinessListReceived(List<Business> list){
// list holds your data
}
});