The Wayback Machine - https://web.archive.org/web/20240927062204/https://www.geeksforgeeks.org/dagger-2-android-example-using-retrofit/
Open In App

Dagger 2 Android Example using Retrofit

Last Updated : 21 Dec, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Dagger 2 Android implementation is easier and it is based on Dependency Injection Architecture. Dependency Injection is a design pattern, which is a concept of Object-Oriented Programming, where we don’t create an object of another class inside a class using the new keyword (for Java). Instead, we supply the needed object from the outside. It is a fully static, compile-time dependency injection framework for both Java and Android. It is an adaptation of an earlier version created by Square and now maintained by Google. Note that we are going to implement this project using the Java language. 

The Theoretical Part About Dagger 2

  • Dependency Provider: Dependencies are the objects that we need to instantiate inside a class. We cannot instantiate a class inside a class. The person who will provide us the objects that are called dependencies is called Dependency Provider. dagger2 is the class that you want to make a Dependency Provider, It needs to annotate it with the @Module annotation.
  • Dependency Consumer: Dependency consumer is a class where we need to instantiate the objects. Dagger will provide the dependency, and for this, we just need to annotate the object declaration with @Inject.
  • Component: The connection between our dependency provider and dependency consumer is provided via an interface by annotating it with @Component. And the rest of the thing will be done by Dagger.

Example

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Before going to the coding section first you have to do some pre-task

Before going to the coding section first you have to do some pre-task. Go to the app > res > values > colors.xml section and set the colors for your app.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#0F9D58</color>
    <color name="colorPrimaryDark">#0F9D58</color>
    <color name="colorAccent">#FF4081</color>
</resources>


Go to the Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “Sync Now” on the above pop up.

// these two lines are added for retrofit

implementation ‘com.squareup.retrofit2:retrofit:2.7.2’

implementation ‘com.squareup.retrofit2:converter-gson:2.7.2’

// these two lines are added for dagger

implementation ‘com.google.dagger:dagger:2.13’

annotationProcessor ‘com.google.dagger:dagger-compiler:2.13’

Go to the app > manifests > AndroidManifests.xml section and allow “Internet Permission“. Below is the code for the AndroidManifests.xml file.

<!– the internet permission , then only api calls can be retrieved –>

<uses-permission android:name=”android.permission.INTERNET” />

Step 3: Designing the UI

Below is the code for the activity_main.xml file. This will be under the app > src > main > res > layout folder. Depends upon different resolutions, sometimes we may need to have it under layout > hdpi or layout > xhdpi folders, etc.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <ListView
        android:id="@+id/listViewCountries"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark"/>
  
</RelativeLayout>


Step 4: Working with the Java file

App Module.java file:

In Retrofit(Retrofit is a REST Client for Java and Android), we need the context object. To supply the objects, so here we will create this module that will give us the Context.

Java




import android.app.Application;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
  
@Module
class AppModule {
    private Application mApplication;
  
    AppModule(Application mApplication) {
        this.mApplication = mApplication;
    }
  
    @Provides
    @Singleton
    Application provideApplication() {
        return mApplication;
    }
}


With the dagger, we need to annotate @Singleton when we want a single instance only.

API Module.java:

For Retrofit, we need a bunch of things. Cache, Gson, OkHttpClient, and the Retrofit itself. So we will define the providers for these objects here in this module.

  • Gson: It is a Java library that can be used to convert Java Objects into their JSON representation.
  • Okhttp: works with Retrofit, which is a brilliant API for REST.

Java




import android.app.Application;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
  
@Module
class ApiModule {
  
    String mBaseUrl;
  
    ApiModule(String mBaseUrl) {
        this.mBaseUrl = mBaseUrl;
    }
  
  
    @Provides
    @Singleton
    Cache provideHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024;
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }
  
    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }
  
    @Provides
    @Singleton
    OkHttpClient provideOkhttpClient(Cache cache) {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.cache(cache);
        return client.build();
    }
  
    @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
    }
}


Building Component: ApiComponent.java

Java




import javax.inject.Singleton;
import dagger.Component;
  
@Singleton
@Component(modules = {AppModule.class, ApiModule.class})
public interface ApiComponent {
    void inject(MainActivity activity);
}


We will inject in the MainActivity. We also define all the modules using the @Component annotation as we can see in the code.

MyApplication.java file:

Java




import android.app.Application;
  
public class MyApplication extends Application {
  
    private ApiComponent mApiComponent;
  
    @Override
    public void onCreate() {
        super.onCreate();
        // https://restcountries.eu/rest/v2/all -> It will list all the country details
        mApiComponent = DaggerApiComponent.builder()
                .appModule(new AppModule(this))
                .apiModule(new ApiModule("https://restcountries.eu/rest/v2/"))
                .build();
    }
  
    public ApiComponent getNetComponent() {
        return mApiComponent;
    }
}


MainActivity.java file:

Java




import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import javax.inject.Inject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
  
public class MainActivity extends AppCompatActivity {
  
    // injecting retrofit
    @Inject Retrofit retrofit;
    ListView listView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
          // injecting here
        ((MyApplication) getApplication()).getNetComponent().inject(this);
        listView = (ListView) findViewById(R.id.listViewCountries);
        getCountries();
    }
  
    private void getCountries() {
        Api api = retrofit.create(Api.class);
          
          // Call<List<Country>> call = RetrofitClient.getInstance().getMyApi().getCountries();
        Call<List<Country>> call = api.getCountries();
        call.enqueue(new Callback<List<Country>>() {
            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) {
                List<Country> countryList = response.body();
  
                // Creating an String array for the ListView
                String[] countries = new String[countryList.size()];
  
                // looping through all the countries and inserting 
                  // the names inside the string array
                for (int i = 0; i < countryList.size(); i++) {
                    countries[i] = countryList.get(i).getName();
                }
  
                // displaying the string array into listview
                listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, countries));
            }
  
            @Override
            public void onFailure(Call<List<Country>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}


Output:

Example Request:

https://restcountries.eu/rest/v2/all will provide the output as shown in the image. We will take the country name from that

Example Response:

The output of the above REST API URL

As we are taking country names only we will get as a list like Afghanistan,…..India etc., On executing the above code, we can able to get the output as shown below.

You can find the source code: https://github.com/raj123raj/dagger-retrofit



Similar Reads

Dagger Hilt in Android with Example
Dependency Injection (DI) is a design pattern to decouple the conventional dependency relationship between objects. When it comes to DI in android Dagger always takes a lead. But it is very complex and requires a lot of boilerplate codes in order to set up the Dagger. So, to overcome this problem Hilt was introduced. Dagger Hilt simplifies the whol
8 min read
How Does the Dagger Work in Android?
When we create a new Android Project, eventually we start accumulating different-different dependencies to get certain functionalities, but over time managing them becomes cumbersome, thus an injection framework like Dagger comes into play. However, setting up an injection service like Dagger requires much amount of boilerplate code and has a very
5 min read
Dependency Injection with Dagger 2 in Android
If there are two classes, class A and class B and class A depends on class B then class B is called dependent for class A. So, Every time we want to access class B in class A we need to create an instance of class B in Class A or use static factory methods to access class A. But this will make our code tight coupled, difficult to manage, and test.
7 min read
Android - Component in Dagger
In order to fully understand the concept of Component in Dagger, we have to first go through a brief about Dagger itself. Now according to the documentation Dagger is defined as follows : ‘Manual dependency injection or service locators in an Android app can be problematic depending on the size of your project. You can limit your project's complexi
6 min read
How to Use Dagger Library in Android App?
When we create a new Android Project, eventually we start accumulating different-different dependencies to get certain functionalities, but over time managing them becomes cumbersome, thus an injection framework like Dagger comes into play. However, setting up an injection service like Dagger requires much amount of boilerplate code and has a very
5 min read
How to Use Dagger in Dynamic Feature Module in Android?
In our previous article, we learned how to set up dagger in an Android project with a multi-module architecture. Click here to see how we can use Dagger in Multi-Module Architecture. We will be expanding on the project that we worked on in our previous project. But first, we must learn how to create and configure a dynamic-feature module. Click her
3 min read
Why to Use the Dependency Injection Framework like Dagger in Android?
In our project, we may or may not have used a dependency framework. In this blog, we will discuss why we need a dependency framework and why using one in our project is beneficial. We can assume that this is an interview question in this case. In this Geeks for Geeks article, we will respond to it by discussing the following topics: Why do we use a
5 min read
Dagger 2 @Inject and @Component Annotations in Android
Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bough
3 min read
How to Use Dagger in a Multi-Module Project in Android?
We know about the Dagger dependency injection framework and how to use it in a single module project. Dagger is basically used for reducing or completely getting rid of the unnecessary boilerplate code. We have already seen step-by-step usage of the dagger library in android, check it here. But in this article what we are going to learn is much mor
6 min read
Assisted Dependency Injection in ViewModel with Dagger-Hilt in Android
If you use Dagger-Hilt Dependency Injection in your android project then you must have encountered a case where you want to manually supply some parameters to construct an object in order to inject it. Generally when we inject a dependency/object in a class then the Dagger-Hilt framework construct it behind the scenes by automatically passing speci
6 min read
How to Update Data in API using Retrofit in Android using Jetpack Compose?
Android applications use APIs within Android Applications to access data from databases. We can perform several operations using APIs such as Reading, Writing, and Updating our Data in the Database. In this article, we will take a look at How to Update Data in API using Retrofit in Android using Jetpack Compose. Note: If you are seeking Java code f
9 min read
How to Post Data to API using Retrofit in Android using Jetpack Compose?
APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retrofit in Android using Jetpack Compose. Note: If you
9 min read
How to Update Data in API using Retrofit in Android?
We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Retrofit library for updating our data in our API. What we are going to build in this article? We will be building a simple application in which we will be di
6 min read
How to Post Data to API using Retrofit in Android?
We have seen reading data from API in our Android app in Android Studio. For reading data from API, we use GET request to read our data which is in JSON format. In this article, we will take a look at adding data to REST API in our Android App in Android Studio. What we are going to build in this article? We will be building a simple application in
6 min read
JSON Parsing in Android using Retrofit Library
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonOb
6 min read
How to Extract Data from JSON Array in Android using Retrofit Library?
In the previous article on JSON Parsing in Android using Retrofit Library, we have seen how we can get the data from JSON Object in our android app and display that JSON Object in our app. In this article, we will take a look at How to extract data from JSON Array and display that in our app. Note: To extract Data from JSON Array in Android using V
9 min read
Android - JSON Parsing using Retrofit Library with Kotlin
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look at JSON Parsing in Android applications using Kotl
6 min read
Android - Extract Data From JSON Array using Retrofit Library with Kotlin
In the android application, the response from the server is in the form of JSON. We can get to see either a JSON Array or a JSON Object in the response. JSON Array is the list of data which is having similar JSON objects. In the previous article, we have taken a look at How to parse data from JSON Object in android applications using Kotlin. In thi
7 min read
Android - JSON Parsing Using Retrofit Library with Jetpack Compose
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look at JSON Parsing in Android applications using Jetp
9 min read
Android - Extract Data From JSON Array using Retrofit Library with Jetpack Compose
JSON responses are of 2 types i.e. JSON Object and JSON Array. JSON Array consists of individual JSON objects which are having same similar structure but have different values within it. JSON Array is used to parse the data in the form of a list or an array. In the previous article, we have taken a look at How to extract data from JSON Object in An
6 min read
Android - Build a Movie App using Retrofit and MVVM Architecture with Kotlin
Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. The separate code layers of MVVM are: Model: This layer is responsible for the a
5 min read
How to Build a Stock Market News Android App using Retrofit?
Building a stock market news app can be a great way to stay informed about the latest developments in the financial world. This article will explore how to build a simple news app using Kotlin and Retrofit. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-cont
12 min read
How to GET Data From API using Retrofit Library in Android?
A GET request is one of the HTTP request methods that can be used to retrieve data from a server. In an API context, a GET request is typically used to retrieve a specific resource or a collection of resources from a server. When a client makes a GET request to a server, it sends a request message that contains the URL of the desired resource along
7 min read
Android - POST Raw Whole JSON in the Body of a Retrofit Request
REST APIs provide us a functionality with the help of which we can add data to our database using REST API. For posting this data to our database we have to use the Post method of REST API to post our data. We can post data to our API in different formats. In this article, we will take a look at How to Post raw whole JSON in the body of a Retrofit
8 min read
Retrofit with Kotlin Coroutine in Android
Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version
4 min read
Difference Between Dagger, Hilt, Koin and Pure Dependency Injection
It is often an overwhelming task to choose the most suitable dependency injection framework for your project, as there are a variety of popular and widely used frameworks on the market. Dagger, Hilt, Koin, and Pure Dependency Injection are some of the most popular frameworks currently in use. What is Dagger? Dagger is an open-source, lightweight de
5 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. How to use RecyclerView as GridView? While implementing Recycler view in
6 min read
CardView using RecyclerView in Android with Example
RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on the implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. CardView: CardView is an extend
9 min read
GridView Using BaseAdapter in Android with Example
Here, we are designing an Android app to demonstrate the use of GridView layout. The GridView layout is a ViewGroup that groups view in a two-dimensional scrolling grid of rows and columns. Items in the grid view are inserted using a ListAdapter. The layout by default is scrollable and we don't need to use ScrollView. An example of GridView is your
7 min read
Article Tags :
Practice Tags :