如何从改装api get call返回对象

问题描述 投票:0回答:1

我试图通过改装从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() + "\n\n";

                textViewResult.append(content);
            }
            businessesList = businesses;
        }

        @Override
        public void onFailure(Call<List<Business>> call, Throwable t) {
            call.cancel();
            textViewResult.setText(t.getMessage());
        }
    });
}

我正在尝试获得业务响应并将其返回。谁能帮我?感到沮丧:(

api get retrofit2 return-value android-studio-2.0
1个回答
0
投票

执行Retrofit调用的方式是异步的 - 使用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
     }
});
© www.soinside.com 2019 - 2024. All rights reserved.