How to read local.properties android in a java file… here is a solution to the problem.
How to read local.properties android in a java file
I want to add a custom field in local.properties
, eg
debug.username=test123
debug.password=abcd1234
You can add a .properties
file in the assets folder and read it easily.
Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
Properties properties = null;
InputStream inputStream = assetManager.open(fileName);
properties = new Properties();
properties.load(inputStream);
But don’t want to.
Because I want each of our team members to use local.properties to specify custom properties.
This is not part of a version control system.
So how do you read local.properties
in the root directory of the Gradle based Android project in a Java file at runtime?
Solution
I
know this is an old issue, but I’ve had the same thing recently and I thought I’d share my solution :
- Set the values in your local.properties file.
- Read the value in the Gradle build script and set it to
the BuildConfig
constant. - Access the
BuildConfig
constants in Java code.
local.properties
username=myUsername
build.gradle:
def getUsername() {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
return properties.getProperty("username");
}
android {
defaultConfig {
buildConfigField "String", "USERNAME", "\""+getUsername()+"\""
}
}
Sample Java class:
package your.package.name;
class MyClass {
String getUsername() {
return BuildConfig.USERNAME; Will return "myUsername"
}
}