Reputation: 2938
I have a project in Android Studio with a couple of modules.
app
module. With apply plugin: 'com.android.application'
.androidLibrary
module. With apply plugin: 'com.android.library'
.javaLibrary
module. With apply plugin: 'java'
.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...
mysuperhost=superhost
systemProp.mysuperhost=superhost
ORG_GRADLE_PROJECT_mysuperhost=superhost
org.gradle.project.mysuperhost=superhost
... and tried to read them this way with no success:
System.getenv("mysuperhost");
System.getProperty("mysuperhost");
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
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
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