Search code examples
androidgradlekotlingradle-kotlin-dsl

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.


Solution

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