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.
The Navigation component provides a Kotlin-based domain-specific language, or DSL, that relies on Kotlin's type-safe builders. This API allows you to declaratively compose your graph in your Kotlin code, rather than inside an XML resource. This can be useful if you wish to build your app's navigation dynamically.
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.
Kotlin DSL brings the simplicity of the Kotlin language syntax and rich API set right into the script files on top of that code completion makes it perfect to work with Gradle script files. We will use this to manage our dependencies and project settings configurations more elegantly.
Okay. I found solutions.
For Android Projects :
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
val key: String = gradleLocalProperties(rootDir).getProperty("key")
buildTypes
I write it:buildTypes {
getByName("debug") {
buildConfigField("String", "key", key)
}
}
override fun onCreate() {
super.onCreate()
val key = BuildConfig.key
}
For Kotlin Projects:
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)
}
task("printKey") {
doLast {
val key = getLocalProperty("key")
println(key)
}
}
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.*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With