Jorge E. Hernández
Jorge E. Hernández

Reputation: 2938

How to read value from gradle.properties in java module?

I have a project in Android Studio with a couple of modules.

I want to declare some variables in the project gradle.properties file and be able to read them from the javaLibrary module.

I have declared the properties in the following ways according this documentation...

... and tried to read them this way with no success:

I know how to read properties from the BuildConfig class, but this is a generateed class in the app module (with apply plugin: 'com.android.application'), so this does not work for this particular case.

Upvotes: 3

Views: 7466

Answers (2)

akirakaze
akirakaze

Reputation: 106

If you have some value inside of the your gradle.properties file like mysuperhost=superhost then write the following lines in the your build.gradle file (to grab property from gradle.properties file and add it into BuildConfig.java class):

// ...
// ...

android {
    // Just for example
    compileSdkVersion 23
    // Just for example
    buildToolsVersion "23.0.2"

    // ...
    // ...

    defaultConfig {
        // Just for example
        minSdkVersion 14
        // Just for example
        targetSdkVersion 23

        // This is the main idea
        buildConfigField('String', 'MY_SUPER_HOST', "\"${mysuperhost}\"")

        // ...
        // ...
    }

    // ...
    // ...
}

// ...
// ...

After that build your project and you are able to use your value via BuildConfig.MY_SUPER_HOST

Upvotes: 7

Doug Stevenson
Doug Stevenson

Reputation: 317467

Your statement about being unable to use BuildConfig is not entirely accurate, as you can use Java reflection to find the public static members of BuildConfig as long as you know its fully qualified package.

Say the full package name of your generated BuildConfig is com.company.app.BuildConfig. You can get its Class object with:

Class<?> klass = Class.forName("com.company.app.BuildConfig");

Then you can use that Class object to pick out the fields of it by name:

Field field = klass.getDeclaredField("BUILD_TYPE");

Then you can get its value:

String value = field.get(null);

Upvotes: 1

Related Questions