32

I want to retreive key from local.properties file that looks like :

sdk.dir=C\:\\Users\\i30mb1\\AppData\\Local\\Android\\Sdk
key="xxx"

and save this value in my BuildConfig.java via gradle Kotlin DSL. And later get access to this field from my project.

i30mb1
  • 3,894
  • 3
  • 18
  • 34

4 Answers4

43

Okay. I found solutions.

For Android Projects :

  1. In my build.gradle.kts I create a value that retrieves my key:
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties

val key: String = gradleLocalProperties(rootDir).getProperty("key")
  1. And in the block buildTypes I write it:
buildTypes {
 getByName("debug") {
    buildConfigField("String", "key", key)
   }
}
  1. And in my Activity now I can retrieve this value:
override fun onCreate() {
    super.onCreate()
    val key = BuildConfig.key
}

For Kotlin Projects:

  1. We can create an extension that help us to retrieve desired key:
fun Project.getLocalProperty(key: String, file: String = "local.properties"): Any {
    val properties = java.util.Properties()
    val localProperties = File(file)
    if (localProperties.isFile) {
        java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8).use { reader ->
            properties.load(reader)
        }
    } else error("File from not found")

    return properties.getProperty(key)
}
  1. And use this extension when we would like
task("printKey") {
   doLast {
       val key = getLocalProperty("key")
       println(key)
   }
}
i30mb1
  • 3,894
  • 3
  • 18
  • 34
31

If you don't have access to gradleLocalProperties (it's only accessible for android projects):

val prop = Properties().apply {
    load(FileInputStream(File(rootProject.rootDir, "local.properties")))
}
println("Property:" + prop.getProperty("propertyName"))

Don't forget imports:

import java.io.File
import java.io.FileInputStream
import java.util.*
Michał Klimczak
  • 12,674
  • 8
  • 66
  • 99
3

put your property in local.properties

and in build.gradle(app).kts file reference it as such: gradleLocalProperties(rootDir).getProperty("YOUR_PROP_NAME")

0

for me the complete solution in android projects was :

1 - put your key in local properties.

2 - in build.gradle.kts => add 2 lines

val key: String = gradleLocalProperties(rootDir).getProperty("KEY") ?: ""
buildConfigField("String", "KEY", "\"$key\"")

== now you can get your key in code like this:

val key = BuildConfig.KEY
Ahmed Nabil
  • 136
  • 1
  • 7