Reprator
Reprator

Reputation: 3069

access Properties file located in app folder in src file in android

I want to access a property file from a module root, but failed to find any suitable example to access the property file as many only tells how to access from asset in android. My app structure is as follows,

├── app
│   ├── key.properties  <--It is my property file, which contains app keys,to be used in app 
│   └── src             <-- Here i want to access the key.properties to access some keys 
├── build.gradle
├── gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
└── local.properties

Upvotes: 1

Views: 1286

Answers (1)

Philippe A
Philippe A

Reputation: 1252

Mike M is correct in that you should use gitignore to hide your file from git so it won't be pushed on your repository.

To expand a bit on this, here's a solution to have gradle load your properties during the build, and make them available to your app via BuildConfig.

1/ app/build.gradle

Before the android { ... } plugin, add:

Properties props = new Properties()
try {
    props.load(file('keys.properties').newDataInputStream())
} catch (Exception ex) {
    throw new GradleException("Missing keys.properties file.");
}

2/ app/build.gradle

In your buildTypes config, add

buildTypes {
    debug {
        buildConfigField "String", "KEY_MY_PROP", "\"${props.getProperty("myPropKey")}\""
    }
    release {
        buildConfigField "String", "KEY_MY_PROP", "\"${props.getProperty("myPropKey")}\""
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

3/ Any class in your app

Your key is accessible as BuildConfig.KEY_MY_PROP

Upvotes: 3

Related Questions