I am trying to switch my gradle files to Kotlin DSL. My project is making call to an API.
In build.gradle(app) I had a function to retrieve an api key stored in an other
file keys.properties.
After some problem (for example) I rewrote the function to get the
key. I wrote the following function in build.gradle.kts:
import import java.io.File
fun readFileLineByLineUsingForEachLine2(fileName: String): HashMap<String, String>{
val items = HashMap<String, String>()
File(fileName).forEachLine {
items[it.split("=")[0]] = it.split("=")[1]
}
return items
}
Then I set a variable to hold the value of a particular key:
buildConfigField(String!, "API_KEY", returnMapOfKeys()["API_KEY"])
After fixing some errors I am stuck with the following one:
app/build.gradle.kts:49:36: Expecting ')'
which point on the line above with buildConfigField.
Does someone know where is this error ?
Or does someone know how to retrieve keys from files with Kotlin DSL ?
I solved my problem (it seems so.. check the edit!!). I ended up with the following function:
// Retrieve key for api
fun getApiKey(): String {
val items = HashMap<String, String>()
val f = File("keys.properties")
f.forEachLine {
items[it.split("=")[0]] = it.split("=")[1]
}
return items["API_KEY"]!!
}
And then I call buildConfigField as follow:
buildConfigField("String", "API_KEY", getApiKey())
There are no errors anymore on this part.
Once I have fixed all errors in the build.gradle.kts, the build of my project return that the file keys.properties could not be found: I had to fix my function getApiKey. Finally I could build and run my project with the following implementation:
// Return value of api key stored in `app/keys.properties`
fun getApiKey(): String {
val items = HashMap<String, String>()
val fl = rootProject.file("app/keys.properties")
(fl.exists())?.let {
fl.forEachLine {
items[it.split("=")[0]] = it.split("=")[1]
}
}
return items["API_KEY"]!!
}
This function is far to be good with all its hardcoded stuff but it allows to build my project.
In your kts file, first import
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.util.Properties
then you can do this:
fun getApiKey(): String {
val fl = rootProject.file("gradle.properties") <- the path for the file where your key is.
if (fl.exists()) {
val properties = Properties()
properties.load(FileInputStream(fl))
return properties.getProperty("API_KEY") <- the name your give to it
} else {
throw FileNotFoundException()
}
}
Now you call use it: buildConfigField("String", "API_KEY", getApiKey())
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