How to return object from retrofit api get call

2.6k Views Asked by At

I am trying to get list of objects from api call with retrofit but i just cant find the way to do so :( This is the function i built:

 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());
        }
    });
}

I am trying to get the businesses response and return it. can anyone help me? Feeling frustrated :(

1

There are 1 best solutions below

0
Fred On

The way your executing the Retrofit call is asynchronous - using call.enqueue. there's nothing wrong with this approach. In fact it's perhaps the best option, since network calls can take a while and you don't want to block unnecessarily.

Unfortunately, this means you cannot return the result from the function. In most scenarios, if you did, the call would likely finish after the return making your return useless.

There are several ways to deal with this, the simplest one is to use callbacks. For example:

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());
    }
  });
}

You can then call it like so:

getBusinesses(new OnBusinessListReceivedCallback() {
     public void onBusinessListReceived(List<Business> list){
        // list holds your data
     }
});