Retrofit with Dagger 2 for Android


Retrofit

Retrofit is type-safe REST client for Android and Java which aims to make it easier to consume RESTful web services.

URL Manipulation:


//ex: api/users?@GET("api/users?")
Call<UsersModel> getAllUser();

//ex: api/1/users@GET("api/{id}/users")
Call<List<User>> groupList2(@Path("id") int groupId);

//ex: api/1/users@GET("api/{id}/users")
Call<List<User>> groupList1(@Path("id") int groupId);

//ex: api/1/users?sort@GET("api/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

//Passing multiple query params@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

//Request body@POST("users/new")
Call<User> createUser(@Body User user);

//FORM ENCODED AND MULTIPART@FormUrlEncoded@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

//Multipart form data@Multipart@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

//Single Header passing@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<UsersModel> getAllUser2();

//Multiple Headers passing@Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"})
@GET("users/{username}")
Call<User> getUser1(@Path("username") String username);

//Dynamic header passing @Header annotation@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)

//Dynamic multiple headers passing using @HeaderMap annotation@GET("user")
Call<User> getUser(@HeaderMap Map<String, String> headers);

Gradle Dependency for Retrofit and Gson Converter:
implementation 'com.squareup.retrofit2:retrofit:2.7.0'
implementation 'com.squareup.retrofit2:converter-gson:2.7.0'

https://square.github.io/retrofit/




Sample Json Data url: https://reqres.in/api/users



Create a Data/Model/POJO class for User Object:




Create another POJO/Model class for the whole response of user list



Create an interface for Retrofit Api Service calls






Create a Network Module then Added in an app-component interface and app-controller class




import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

@Modulepublic class NetworkModule {

    @Provides    @Singleton    Retrofit provideRetrofit() {
        return new Retrofit.Builder().baseUrl("https://reqres.in/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Provides    @Singleton    RetrofitApiService provideRetrofitApiService(Retrofit retrofit) {
        return retrofit.create(RetrofitApiService.class);
    }

}




Added in AppComponent interface

@Singleton  //Singleton annotation@Component(modules = {AppModule.class, NetworkModule.class, AppContainerModule.class})    //Dagger component annotationpublic interface AppComponent {

Added in AppController class

@Overridepublic void onCreate() {
    super.onCreate();
    appComponent = DaggerAppComponent.builder()
            .networkModule(new NetworkModule())
            .appModule(new AppModule(this)) //Set application module            .build();
}


Open the MainActivity class and Inject the RetrofitApiService interface






Result from android device

Full Source code github link : https://github.com/AndroidManikandan5689/Dagger2-Retrofit-Android-Java

Sample APK download link
https://github.com/AndroidManikandan5689/Dagger2-Retrofit-Android-Java/blob/master/apk/dagger2_retrofit_apk.apk


Happy Coding...😊

Comments

Popular posts from this blog

Google Assistant Implementation in Android application with app actions