Search code examples
javaandroidvariablesbuildgradle-task

Can't make gradle task pass value in Java during build time


So i have a task that reads a file and passes its value in a property that is passed in the BuildConfig class, so that it can be accessed through Java classes in Android Studio. When i run the task alone, it prints out the read value that got from the file. When i press "Run" to run my application though, the value of that property remains default in BuildConfig, like the task never ran.

INSIDE build.gradle of Project:

task testVariableInsertion() {
    doLast {
        File file = file('.gitignore')
        println domainName
        domainName = file.text;
        println domainName;
        project.logger.info('task runned NOW!!!!!!!!!!!!!')
    }
}

INSIDE build.gradle of Module 'app':

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.testingproject"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        buildConfigField "String", "DOMAIN_NAME", "${domainName}"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Was expecting that gradle would run the task automatically and that seems the case since i get the log messages if i type "gradlew --info" after build. Is it because it reads the file and by the time it is done reading the value is already passed in the BuildConfig? What am i missing?


Solution

  • Found the answer few days ago, in order for this to work i had to define my task like this:

    def testVariableInsertion = {
            File file = file('.gitignore')
            println domainName
            domainName = file.text;
            println domainName;
            project.logger.info('task runned NOW!!!!!!!!!!!!!')
    }
    

    and call it underneath with

    testVariableInsertion()
    

    I also have my variable domainName inside the 'ext' bracket

    ext {
    domainname = "defaultValue"
    }
    

    and then in the defaultConfig of the app module:

    buildConfigField "String", "DOMAIN_NAME", rootProject.ext.domainName