AbKDs AbKDs - 1 year ago 350
Android Question

Using Call Enqueue function in Retrofit

I am using

for my app. Now every tutorial on Retrofit I found on web is based on earlier
and there was no
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 {
Call<MovieResponse> getMovieResponse(@Query("sort_by") String sortKey,
@Query("api_key") String apiKey);

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

void updateMovies() {
Retrofit retrofit = new Retrofit.Builder()

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

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

call.enqueue(new Callback<MovieResponse>() {
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");
Log.d(LOG_TAG, "Response returned by website is : " + response.code());

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
object is returned by the movieDB API which contains an array of
s and some extra information. I am implementing it in such a way so that once I get the response in
from there I can extract using the
which will return a list of movies.

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

Answer Source

With Retrofit 2, onResponse is called even if there is a failure. You check response.isSuccess(), but if it's false, in your code you just log it. 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 as 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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download