android – How to use variable in gradle files?-ThrowExceptions

Exception or error:

I’d like to declare an API version my test application uses to build it and also display it in the application.

So I declared the version like that in the project’s build.gradle:

buildscript {
    ext {
        ...
        api_version = '0.2.9'
    }
    ...
}

Then in my app’s build gradle, I use it:

android {
    ....
    buildTypes {
        release {
            ...
            buildConfigField "String", "api_version", "$api_version"
        }
        debug {
            ...
            buildConfigField "String", "api_version", "$api_version"
        }
    }
}

dependencies {
    ....    
    implementation "com.example.service:my_api:$api_version"
}

And finally, I use it in my app:

    supportActionBar?.title = """${getString(R.string.app_name)} $VERSION_NAME API:${BuildConfig.api_version}"""

But on build I get the following error in the generated BuildConfig.java file:

public final class BuildConfig {

  // Fields from build type: debug
  public static final String api_version = 0.2.9;
}

The error is

......\BuildConfig.java
Error:(14, 54) error: ';' expected

I suppose BuildConfig.java should contain:

public static final String api_version = "0.2.9";

But I don’t understand how to write it.

How to solve:

In fact the right syntax is:

buildTypes {
    release {
        ...
        buildConfigField "String", "api_version", "\"$api_version\""
    }
    debug {
        ...
        buildConfigField "String", "api_version", "\"$api_version\""
    }
}

###

use like this

 buildscript {  

 }
 ext {
   androidCompileSdkVersion = 26
   androidBuildToolsVersion = '26.0.2'
   androidMinSdkVersion = 17
   androidTargetSdkVersion = 26
}

you can access like rootProject.ext.androidCompileSdkVersion

###

Use the following structure.

buildscript{
.........
}
android{
defaultConfig{
.....
}
buildTypes{
....
}
}

def support_package_version = "27.0.2"

dependencies{
.......
    implementation "com.android.support:appcompat-v7:${support_package_version}"
..........
.......
}

###

I used variable like this way.

Declare a variable called DAGER_VERSION and give it a value.(String)

def DAGER_VERSION = “2.21”

In android app.gradle file,inside dependencies block

you should write this way.

You need to put double quotation to use a variable in Groovy.

implementation "com.google.dagger:dagger:${DAGER_VERSION}"
annotationProcessor "com.google.dagger:dagger-compiler:${DAGER_VERSION}"

###

Try using double qoutes when you declare the variable.

buildscript {
    ext {
        ...
        api_version = "0.2.9"
    }
    ...
}

Leave a Reply

Your email address will not be published. Required fields are marked *