My Retrofit call.enque() method is getting skipped over entirely, not sure why

后端 未结 2 910
一向
一向 2021-01-25 10:16

I\'m making a call using Retrofit\'s enqueue() method. I\'m calling my refreshImages() in my MainActivity\'s onCreate(), refreshImag

2条回答
  •  忘掉有多难
    2021-01-25 10:40

    Change your call to the synchronous retrofit API :

    public static List getImageIds(int size) {
        Call call = flickrService.getPhotos(apiKey, format, "1");
        photoIds = new ArrayList();
    
        PhotosList photosList = call.execute().body();
        List photos = photosList.getPhotos().getPhoto();
    
        for(Photo photo : photos) {
            Log.d("TEMP_TAG", "adding photo id to list: " + photo.getId());
            photoIds.add(photo.getId());
        }
        Log.d("TEMP_TAG", "it's getting here too");
        return photoIds;
    }
    

    Please note that you need to call this method on an AsyncTask

    EDIT

    You could also continue to use enqueue, but you need to provide an "onFinish" hook, so you know when your data has been received and then you "notify" the client with the data:

    //interface por communication
    public interface ImageIdsCallBack {
       public void onFinish( List photoIds );
    }
    

    Then you receive this interface and send data:

    public static List getImageIds(int size, final ImageIdsCallBack callback) {
        Call call = flickrService.getPhotos(apiKey, format, "1");
        photoIds = new ArrayList();
    
        call.enqueue(new Callback(){
            @Override
            public void onResponse(Call call, Response response) {
                PhotosList photosList = response.body();
                List photos = photosList.getPhotos().getPhoto();
    
                for(Photo photo : photos) {
                    Log.d("TEMP_TAG", "adding photo id to list: " + photo.getId());
                    photoIds.add(photo.getId());
                }
                //send the data to the caller
                callback.onFinish(photoIds);
            }
    
            @Override
            public void onFailure(Call call, Throwable t) {
                // TODO: Clean up
                Log.d("TEMP_TAG", "Call failed");
            }
        });
        Log.d("TEMP_TAG", "it's getting here too");
        return photoIds;
    }
    

    calling the method :

    getImageIds( 50 , new ImageIdsCallBack() {
         public void onFinish( List photoIds ) {
             //update UI with photoIds
         }
    } );
    

    I typically use a library like EventBus to make it easier, I really recommend it to you.

提交回复
热议问题