This is the second part of Dagger with Retrofit tutorial. In the first part, we’ve achieved the hard part of how to set up dependency injection. In this article, we’re gonna see how we can use the dependencies in our Activity.

So, let’s begin with adding Dagger to our Activity. Below is the MainActivity.

   protected void onCreate(Bundle savedInstanceState) {
       ServiceApplicationComponent component = DaggerServiceApplicationComponent.builder()
               .applicationContextModule(new ApplicationContextModule(this))
       carCategoriesCallback = serviceUtil.getCarCategories();

The interesting part of this code is DaggerApplicationComponentBuilder. You see dagger automatically create a builder pattern for our Component class. In our builder class, we are providing a new instance of ApplicationContextModule because dagger restricted us to provide an instance of that Module which has a constructor parameter.

Dagger provide a way for the fields in your activity, fragments or services to be assigned references simply by annotating the field with an @Inject. After injecting the field dagger2 locate the singletons in the dependency graph to try to find the matching return type. Below is an example of how to @Inject annotation in the field.

Picasso picasso;
ServiceUtil serviceUtil;

This is how you can @inject your fields into activity at the top. Now, lets’ move how you can enqueue your network request with the retrofit.


In enqueue function this represents callback, and for that our MainActivity has to implement callback. One more thing by doing enqueue you are using synchronous call. The synchronous method provides the ability to use return value directly because the operation blocks everything else during the network request.

Note: For non-blocking UI you have to handle the request execution in the separate thread.

Below is the code for retrofit callback interface methods.

public void onResponse(@NonNull Call<CarCategoryResponse> call, @NonNull Response<CarCategoryResponse> response) {
    if (mainProgressBar.getVisibility() == View.VISIBLE)
    if (response.isSuccessful()) {
        if (response.body().getCarCategories() != null && response.body().getCarCategories().size() > 0) {
        } else 
            Toast.makeText(this, "No data found!", Toast.LENGTH_SHORT).show();        
    } else 
        Toast.makeText(this, "Communication error internet not connect!", Toast.LENGTH_SHORT).show();    

public void onFailure(@NonNull Call<CarCategoryResponse> call, @NonNull Throwable t) {
    if (mainProgressBar.getVisibility() == View.VISIBLE)
    Toast.makeText(this, "Communication error internet not connect!", Toast.LENGTH_SHORT).show();

If the call succeeds the callback will come into the onResponse method. If any error occurs in the request callback will go into the onFailure method. Now in the onResponse method, we need to add data in the  RecyclerView Adapter.


public class CarCategoryAdapter extends RecyclerView.Adapter<CarCategoryViewHolder> {

    private List<CarCategoryResponse.CarCategory> carCategories;
    private final LayoutInflater layoutInflater;

    public CarCategoryAdapter(List<CarCategoryResponse.CarCategory> carCategories, final Context context) {
        this.carCategories = carCategories;
        this.layoutInflater = LayoutInflater.from(context);

    public CarCategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new CarCategoryViewHolder(layoutInflater.inflate(R.layout.list_item_single_view, parent, false));

    public void onBindViewHolder(@NonNull CarCategoryViewHolder holder, int position) {
        CarCategoryResponse.CarCategory carCategory = carCategories.get(position);
        holder.getBase_fare().setText(String.valueOf("Rs ").concat(carCategory.getBaseFare()));
        holder.getRate_per_km().setText(String.valueOf("Rs ").concat(carCategory.getRatePerKm()));
        holder.getRate_per_min().setText(String.valueOf("Rs ").concat(carCategory.getRatePerMin()));

    public int getItemCount() {
        return carCategories.size();

The Adapter provides a binding for an app specific data set to views that are displayed in a RecyclerView. In the onBindViewHolderwe update the contents of itemView to reflect the item at the given position.


public class CarCategoryViewHolder extends RecyclerView.ViewHolder {

    private TextView car_category, rate_per_min, rate_per_km, base_fare;

    public CarCategoryViewHolder(View itemView) {
        car_category = itemView.findViewById(;
        rate_per_min = itemView.findViewById(;
        rate_per_km = itemView.findViewById(;
        base_fare = itemView.findViewById(;

    public TextView getCar_category() {
        return car_category;

    public TextView getRate_per_min() {
        return rate_per_min;

    public TextView getRate_per_km() {
        return rate_per_km;

    public TextView getBase_fare() {
        return base_fare;

The ViewHolder describes an itemView and metadata about its place within a RecyclerView. In CarCategoryViewHolder we’re simply finding the views and set it to its relevant field.


public class CarCategoryResponse {

    private List<CarCategory> carCategories;

    public List<CarCategory> getCarCategories() {
        return carCategories;

    public class CarCategory {

        private int id;
        private String name;
        private String ratePerKm;
        private String ratePerMin;
        private String baseFare;

        public String toString() {
            return "CarCategory{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", ratePerKm=" + ratePerKm +
                    ", ratePerMin='" + ratePerMin + '\'' +
                    ", baseFare='" + baseFare + '\'' +

        public int getId() {
            return id;

        public String getName() {
            return name;

        public void setName(String name) {
   = name;

        public String getRatePerKm() {
            return ratePerKm;

        public String getRatePerMin() {
            return ratePerMin;

        public String getBaseFare() {
            return baseFare;

Alright, this was the complete example of a dagger with the retrofit. If you guys want to learn how to make a network call with retrofit and Rx-Java check out the next article.

I hope this blog gives you a good understanding of the dagger and retrofit. If you’ve any queries regarding this please do comment below.

Thank you for being here and keep reading…


Recommended Training – Treehouse

TreehouseFrom beginner to advanced, our recommended coding training is Treehouse.

Treehouse is an online training service that teaches web design, web development and app development with videos, quizzes and interactive coding exercises.

Treehouse's mission is to bring technology education to those who can't get it, and is committed to helping its students find jobs. If you're looking to turn coding into your career, you should consider Treehouse.


Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, we will receive an affiliate commission. Regardless, we only recommend products or services we use personally and believe will add value to our readers.


I’m a mobile product devsigner (i.e. I consider myself as both a developer and a designer) and user experience/interface engineer. I’m an expert on the Android platform and have been recognized as it by the community.