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

后端 未结 2 847
一向
一向 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<String> getImageIds(int size) {
        Call<PhotosList> call = flickrService.getPhotos(apiKey, format, "1");
        photoIds = new ArrayList<String>();
    
        PhotosList photosList = call.execute().body();
        List<Photo> 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<String> photoIds );
    }
    

    Then you receive this interface and send data:

    public static List<String> getImageIds(int size, final ImageIdsCallBack callback) {
        Call<PhotosList> call = flickrService.getPhotos(apiKey, format, "1");
        photoIds = new ArrayList<String>();
    
        call.enqueue(new Callback<PhotosList>(){
            @Override
            public void onResponse(Call<PhotosList> call, Response<PhotosList> response) {
                PhotosList photosList = response.body();
                List<Photo> 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<PhotosList> 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<String> photoIds ) {
             //update UI with photoIds
         }
    } );
    

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

    0 讨论(0)
  • Correct me if I'm wrong, is this on the main thread? That would pose the problem of not waiting for a response.

    Consider using async

    0 讨论(0)
提交回复
热议问题