Java – Android/Java Retrofit: Class cannot be converted to Callback

Android/Java Retrofit: Class cannot be converted to Callback… here is a solution to the problem.

Android/Java Retrofit: Class cannot be converted to Callback

I’m new to revamping and I’m trying to get a json response to an object named RootObject. The error I’m getting is:

“Error:(21, 44) error: incompatible types: NewsController cannot be
converted to Callback>”

Is anyone making my mistake here now? Thank you for your regards!

public class NewsController {
        public void getNews(){
            Retrofit retrofit = new Retrofit.Builder().baseUrl("apilink").addConverterFactory(GsonConverterFactory.create()).build();
            GetNewsService service = retrofit.create(GetNewsService.class);
            try {
                service. GetNewsItems().enqueue(this); asynchronous
                Response<List<RootObject>> response = service. GetNewsItems().execute(); synchronous
            }
            catch (IOException e){

}
        }
}

Class in which the data is placed:

public class RootObject implements Serializable {
   public ArrayList<Result> results ;
   public int nextId;

public ArrayList<Result> getResults() { return results; }
    public int getNextId() { return nextId; }

public String toString() {
        return String.format("JEEJ" + nextId);
    }
}

Interface:

public interface GetNewsService {
    @GET("/Articles")
    Call<List<RootObject>> GetNewsItems();
}

Solution

First of all
Change your interface to:

public interface GetNewsService { 
  @GET("/Articles") 
  void GetNewsItems(Callback<List<RootObject>> cb);
}

Also change your newsController class.

public class NewsController {
    private RestAdapter restAdapter;
    static final String API_URL = "[Enter your API base url here]";
    public void getNews(){
        OkHttpClient mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(15000,TimeUnit.MILLISECONDS);
        mOkHttpClient.setReadTimeout(15000,TimeUnit.MILLISECONDS);
        restAdapter = new RestAdapter.Builder().setEndpoint(API_URL).setClient(new OkClient(mOkHttpClient)).setLogLevel(RestAdapter.LogLevel.FULL) .build();
        GetNewsService service = restAdapter.create(GetNewsService.class);

Callback<List<RootObject> cb = new Callback<List<RootObject>>() {
          @Override 
          public void success(List<RootObject> rootObjectList, Response response) { 
             whatever you want to do with the fetched news items
          } 

@Override 
          public void failure(RetrofitError error) { 
            whatever you want to do with the error
          } 
        };
        service. GetNewsItems(cb);    
    }
}

You need to add the following dependencies in build.gradle:

compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.squareup.okhttp:okhttp:2.4.0'

Related Problems and Solutions