i30mb1
i30mb1

Reputation: 4786

Read value from local.properties via Kotlin DSL

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.

Upvotes: 53

Views: 33205

Answers (7)

swooby
swooby

Reputation: 3145

Per a 2024 comment in the OP's 2020 self-answer, and to be more precise since Android Studio LadyBug circa 2023/09, the answer for this is now:

import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
val key = gradleLocalProperties(rootDir, providers).getProperty("key")
buildConfigField("String", "key", key)

NOTE the change from gradleLocalProperties(rootDir) to gradleLocalProperties(rootDir, providers)

If your property is not already surrounded by quotes:

buildConfigField("String", "key", "\"$key\"")

To dynamically handle if it is surrounded by quotes:

fun ensureQuoted(s: String) =
    "\"${(if (s.length >= 2 && s.startsWith('"') && s.endsWith('"'))
         s.substring(1, s.lastIndex)
     else s).replace("\"", "\\\"")}\""

buildConfigField("String", "key", ensureQuoted(key))

Upvotes: 0

i30mb1
i30mb1

Reputation: 4786

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, providers).getProperty("key")

NOTE: Prior to 2024 this was:

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)
   }
}

Upvotes: 61

Jean Raymond Daher
Jean Raymond Daher

Reputation: 394

Put your property into local.properties.

In the build.gradle(app).kts file, reference it as such:

gradleLocalProperties(rootDir).getProperty("YOUR_PROP_NAME")

Upvotes: 3

Javier
Javier

Reputation: 1695

To read properties inside the gradle file it can be done with

import java.util.Properties

android {
    compileSdkVersion(Config.Android.compileSdkVersion)
    buildToolsVersion = Config.Android.buildToolsVersion
  
    defaultConfig {
        minSdkVersion(Config.Android.minSdkVersion)
        versionCode = Config.Libs.versionCode
        versionName = Config.Libs.versionName
        setProperty("archivesBaseName", "${project.name}-${versionName}(${versionCode})")

        val projectProperties = readProperties(file("../project.properties"))

        buildConfigField("String", "STATIC_VECTOR", projectProperties["staticVector1"] as String)
    }
  
}

fun readProperties(propertiesFile: File) = Properties().apply {
    propertiesFile.inputStream().use { fis ->
        load(fis)
    }
}

Source

Upvotes: 3

Ganesh Katikar
Ganesh Katikar

Reputation: 2700

I might be late here to answer but out of the above answer one thing is missing is to set buildConfig value to true of buildFeature.

android{
    buildFeatures 
        buildConfig = true
    }
}

In my case what I followed is:

local.properties file

sdk.dir=/home/username/user/software/android-sdk
API_KEY=kE949ziieWGGyk8skRSk93gGd

Also,you need to read and define your build config field in app-level file

build.gradle

android{
    buildTypes {
        release {
           val p = Properties()   
           p.load(project.rootProject.file("local.properties").reader())
           val yourKey: String = p.getProperty("API_KEY") 
           buildConfigField("String", "API_KEY", "\"$yourKey\"")
        }

        debug {
          val p = Properties()   
          p.load(project.rootProject.file("local.properties").reader())
          val yourKey: String = p.getProperty("API_KEY") 
          buildConfigField("String", "API_KEY", "\"$yourKey\"")
        }
    }
}

In the above example note that I have used two different keys for both release and debug build.

Note Important: After all these changes, sync your project, clean the build, re-build it, and then use the build config build like:

BuildConfig.API_KEY

Upvotes: 7

Ahmed Nabil
Ahmed Nabil

Reputation: 161

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

Upvotes: 0

Michał Klimczak
Michał Klimczak

Reputation: 13144

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.*

Upvotes: 49

Related Questions