Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Call Enqueue function in Retrofit

I am using Retrofit-2.0.0 for my app. Now every tutorial on Retrofit I found on web is based on earlier Retrofit and there was no Call<T> interface there. This is the first time I am using Retrofit and I am repeatedly getting null object reference. Here is my network model interface

public interface TMovieDBService {
    @GET("/movie")
    Call<MovieResponse> getMovieResponse(@Query("sort_by") String sortKey,
                             @Query("api_key") String apiKey);
}

And this is my updateMovies() function which updates the list of movies.

void updateMovies() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://api.themoviedb.org/3/discover")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    String sortKey = "popularity.desc";
    TMovieDBService service = retrofit.create(TMovieDBService.class);

    Call<MovieResponse> call = service.getMovieResponse(sortKey, ApiKey.API_KEY);

    call.enqueue(new Callback<MovieResponse>() {
        @Override
        public void onResponse(Response<MovieResponse> response) {
            Log.d(LOG_TAG, "Reached this place");
            if (!response.isSuccess()) {
                Log.d(LOG_TAG, "No Success");
            }
            mMovieList = response.body().getMovies();  // <- response is null here
            // Log.d(LOG_TAG, "Couldn't not reach this place");
            mMovieAdapter.notifyDataSetChanged();
            Log.d(LOG_TAG, "Response returned by website is : " + response.code());
        }

        @Override
        public void onFailure(Throwable t) {
            // Toast for the moment
            // Appropriate error handling code should be present here
            Toast.makeText(getActivity(), "Failed !", Toast.LENGTH_LONG).show();
        }
    });
}

I don't know what to implement in the enqueue function. Very little is given on the retrofit website on how to use the callback. Assume all the other code is working fine. Here MovieResponse object is returned by the movieDB API which contains an array of Movies and some extra information. I am implementing it in such a way so that once I get the response in MovieResponse from there I can extract using the getMovies() which will return a list of movies.

When I run I simply get null object reference because response is null. I tried to search for tutorials on using new Retrofit-2.0.0 especially on using enqueue function but I am out of luck. Plus one more question where should the updateMovies() be called. Can I call it directly in the mainactivity. Does retrofit automatically run the network call on background thread ?

like image 497
abkds Avatar asked Sep 07 '15 05:09

abkds


People also ask

What is call enqueue in retrofit?

enqueue(Callback<T> callback) Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response. Response<T> execute() Synchronously send the request and return its response.

What are the different ways to get callback from retrofit?

Retrofit uses two different callback methods for the two possible outcomes of a network requests: either a failure or a successful request. Retrofit will call the appropriate callback method depending on the result. If the request was successful, Retrofit will also pass you the response of the server.

Does retrofit run on background thread?

Does retrofit run on background thread? Retrofit is a third-party library by Square for communicating with REST APIs over HTTP. Similarly to AsyncTasks , work is done in a background thread, and upon completion it returns the result to the main UI thread.


1 Answers

With Retrofit 2, onResponse is called even if there is a failure. You have checked whether response is not successful by using !response.isSuccess(). But you just logged it - if it's true (i.e. not successful). Instead, you could log response.errorBody().string() to see if api server specifies the error, and you should call something like return to exit onResponse callback, as response.body() couldn't be casted to MovieResponse, hence the null exception.

By the way, your code is correct, but if you just start with Retrofit, it would be simpler to use 1.9 version as 2.0 is still a beta version (very stable though, but lack of tutorials).

like image 51
guillaume_fr Avatar answered Sep 17 '22 00:09

guillaume_fr