Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a local.properties field when declaring a buildConfigField

I have a build.gradle and a local.properties file. I want to declare a value in local.properties, which isn't checked in to version control, to use in build.gradle.

I have the buildConfigField working with:

buildTypes {
    debug {
        buildConfigField "String", "TEST", "test"
    }
}

Unfortunately though, this causes an error:

buildTypes {
    debug {
        buildConfigField "String", "TEST", local.properties.get("test")
    }
}
like image 936
theblang Avatar asked Sep 15 '14 18:09

theblang


People also ask

What is local properties?

sdk.dir=The Sdk Directory path. So local. properties is a file that is generated by Android Studio and it is recommended not to include this in the version control system.

Where is gradle local properties?

Instead, you should store it in the local. properties file, which is located in the root directory of your project and then use the Secrets Gradle Plugin for Android to read the API key.

What is BuildConfigField?

BuildConfigField. Gradle allows buildConfigField lines to define constants. These constants will be accessible at runtime as static fields of the BuildConfig class. This can be used to create flavors by defining all fields within the defaultConfig block, then overriding them for individual build flavors as needed.


1 Answers

It can be achieved like:

def getProps(String propName) {
  def propsFile = rootProject.file('local.properties')
  if (propsFile.exists()) {
    def props = new Properties()
    props.load(new FileInputStream(propsFile))
    return props[propName]
  } else {
    return "";
  }
}

in your buildTypes block:

buildTypes {
    debug {
        buildConfigField "String", "TEST", getProps("test")
    }
}
like image 88
motou Avatar answered Sep 21 '22 04:09

motou