Adrian Ivasku
Adrian Ivasku

Reputation: 1118

Declare/use variable in gradle file - use it in java

I have in my gradle file something like :

String packageName = com.test.free

I want this String variable packageName to use in my java class. I use Android Studio 1.5.1.

Is it possible? How can I transfer this String from gradle to java ?

I have read similar questions here but none of the solutions worked.

Upvotes: 2

Views: 3394

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006539

If that value is really your applicationId, that is already available to you as BuildConfig.APPLICATION_ID.

Otherwise, you can add your own custom fields to BuildConfig. These can include dynamic values:

import static java.util.UUID.randomUUID

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.commonsware.myapplication"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        debug {
            buildConfigField "String", "FOO", '"'+randomUUID()+'"'
        } 

        release {
            buildConfigField "String", "FOO", '"a49f05b4-f55a-4066-a107-9098c9350f43"'
        }
    }
}

Upvotes: 2

Gavriel
Gavriel

Reputation: 19237

Create a gradle task that writes packageName into a java file like:

build.gradle:

task generateGradleValuesJava {
    def java = 
      'public class GradleValues {' +
      '  public static String packageName = "' + project.packageName+ '";' +
      '  }' +
      '}'
    def javaFile = new File('GradleValues.java')
    javaFile.write(java)
}

compileJava.dependsOn generateGradleValuesJava

Compile this file into your jar and use it:

GradleValues.packageName

Upvotes: 2

Related Questions