Search code examples
androiddependency-injectionretrofitretrofit2dagger-hilt

Android Hilt, Retrofit2, and properties file issue


I have a situation that I'm pretty sure is common, but I haven't found a solution for it in any tutorial. Perhaps I am approaching this in totally the wrong way.

I have a module that provides a Retrofit service:

    public static RestService providesRestService(){

        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.somedomain.com")
                .addConverterFactory(GsonConverterFactory.create()).build();

        return retrofit.create(RestService.class);
    }

I want the base URL to be configurable through a properties file. To use a properties file I need the Context so I can access the AssetManager:

AssetManager assetManager = context.getAssets();
assetManager.open("somefile.properties")
...

So I can use the @ApplicationContext annotation:

public static RestService providesRestService(@ApplicationContext){

and that should work for getting properties, but the PROBLEM is that I have another module that provides a class to handles properties files:

static PropertiesUtil providesPropertiesUtil(@ApplicationContext Context context) {
        return new PropertiesUtil(context);

So I want to use that class, but I cannot inject PropertiesUtil into another provides method.

Am I approaching this all wrong?


Solution

  • I went about this all wrong. The better way (in my opinion because you do not need to deal with Context) is to use buildConfig variables.

    In the app/build.gradle file I added:

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
                buildConfigField "String", "REST_BASE_URL", RELEASE_REST_BASE_URL
            }
    
            debug {
                applicationIdSuffix ".debug"
                debuggable true
                buildConfigField "String", "REST_BASE_URL", DEV_REST_BASE_URL
            }
        }
    

    This will create a static String variable you can access via the auto generated BuildConfig.REST_BASE_URL

    You can have add an app/gradle.properties file to have the following:

    DEV_REST_BASE_URL="http://dev.example.com"
    RELEASE_REST_BASE_URL="http://example.com"
    

    Gradle takes the exact value to generate files, so you have to add the quotation marks, or else the BuildConfig.java will be like this:

    public static String REST_BASE_URL=http://example.com;

    instead of

    public static String REST_BASE_URL="http://example.com";