Search code examples
androidgradlegoogle-apiapi-keysecret-key

Unable to access the API key using BuildConfig


I'm using secrets-gradle-plugin to read the API keys that I put in my local.properties.

I've added this code into the root build.gradle

buildscript {
  dependencies {
    classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.0"
  }
}

For app build.gradle

plugins {
  id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
}

android {
  compileSdk 31
...
}

And this is my local.properties

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#
sdk.dir=/Users/xxx/Library/Android/sdk
apiKey=YOUR_API_KEY

Then when I tried to access it from any class/application BuildConfig.apiKey is not there. Am I missing any steps here? Been trying for few hours but doesn't found any way to make this work.


Solution

  • I end up reading the API value in local.properties in app's build.gradle and assigning it to BuildConfig. This is done under defaultConfig tag.

    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream()) 
    buildConfigField "String", "API_KEY", "\"${properties.getProperty('API_KEY')}\""