BuildConfingField string not set correctly - android

I am trying to create a BuildConfingField in my gradle script here my code
def VERSION_NAME = "3.1.0b"
def VERSION=VERSION_NAME+"-"+getDate();
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
minSdkVersion 10
targetSdkVersion 23
setProperty("archivesBaseName",POM_ARTIFACT_ID +"-"+VERSION_NAME+"-"+ getDate())
}
buildTypes {
release {
minifyEnabled false // non usare MAI proguard a meno di non aver ispezionato bene il codice!!
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "String", "VERSION", VERSION
}
debug {
minifyEnabled false
buildConfigField "String", "VERSION",VERSION
}
}
}
def getDate() {
def date = new Date()
def formattedDate = date.format('yyMMddHHmm') //'yyyyMMddHHmmss'
return formattedDate
}
What I get is:
public static final String VERSION = 3.1.0b-1605021144;
This brings compilation error.
Anyone can help on getting the string defined correctly?

Use "\"${VERSION}\"" or '"'+VERSION+'"'.

Related

error porting gradle:2.0.0 to gradle-experimental:0.7.0-beta1?

I have an android studio project, and I'm trying to port gradle from the stable version 2.0.0 to the experimental version 0.7.0-beta1:
This is the working code inside my android tag module my 2.0.0 gradle code:
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.test.myapp"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
ndk {
moduleName "myNativeLib"
}
}
sourceSets.main {
jniLibs.srcDir 'src/main/libs' //set .so files location to libs
jni.srcDirs = [] //disable automatic ndk-build call
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task runSwig(type: Exec, description: 'Run swig config') {
workingDir 'src/main'
commandLine 'cmd', '/c', 'swig.bat'
}
Properties props = new Properties()
props.load(new FileInputStream(file(project.property("KeyStore.properties"))))
signingConfigs {
storeSignature {
storeFile = file(props['KEYSTORE'])
storePassword = props['KEYSTORE_PASSWD']
keyAlias = props['KEYSTORE_MYAPP']
keyPassword = props['KEYSTORE_MYAPP_PASSWD']
}
}
buildTypes {
def SERVER_URL = "SERVER_URL"
debug {
debuggable true
jniDebuggable true
buildConfigField "String", SERVER_URL, "\"http://testusound.eastus.cloudapp.azure.com/androidbackend/checkjson\""
versionNameSuffix getMasterName() + "." + getDate()
}
release {
signingConfig signingConfigs.storeSignature
debuggable false
jniDebuggable false
minifyEnabled false
buildConfigField "String", SERVER_URL, "\"http://www.usound.co/androidbackend/checkjson\""
versionNameSuffix getMasterName()
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
Now here is my attempt to rewrite my code for the expermiental pluggin 0.7.0-beta1:
model {
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig.with {
applicationId "com.test.myapp"
minSdkVersion.apiLevel 15
targetSdkVersion.apiLevel 23
versionCode 1
versionName "1.0"
}
ndk {
moduleName "myNativeLib"
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
task runSwig(type: Exec, description: 'Run swig config') {
workingDir 'src/main'
commandLine 'cmd', '/c', 'swig.bat'
}
buildConfigFields.with {
create() {
type "String"
name "SERVER_URL"
value "\"http://www.myserver.com/backend/checkjson\""
}
}
buildConfigFields.with {
create() {
type "String"
name "TEST_SERVER_URL"
value "\"http://www.mytestserver.com/backend/checkjson\""
}
}
sources {
main {
jni {
source {
srcDir "src"
}
}
jni.srcDirs = [] //disable automatic ndk-build call
}
}
buildTypes {
debug {
debuggable true
jniDebuggable true
buildConfigField $("android.buildConfigFields.TEST_SERVER_URL")
versionNameSuffix getMasterName() + "." + getDate()
}
release {
signingConfig = $("android.signingConfigs.mySignature")
debuggable false
jniDebuggable false
minifyEnabled false
buildConfigField $("android.buildConfigFields.SERVER_URL")
versionNameSuffix getMasterName()
proguardFiles.add(file('proguard-rules.pro'))
}
}
Properties props = new Properties()
props.load(new FileInputStream(file(project.property("KeyStore.properties"))))
}
android.signingConfigs {
create("mySignature")
storeFile = file(props['KEYSTORE'])
storePassword = props['KEYSTORE_PASSWD']
keyAlias = props['KEYSTORE_MYAPP']
keyPassword = props['KEYSTORE_MYAPP_PASSWD']
}
}
I'm getting this error error with the signingConfigs:
Error:Attempt to read a write only view of model of type 'java.lang.Object' given to rule 'android.signingConfigs { ... } # app\build.gradle line 165, column 5'
in my code would be this line:
android.signingConfigs {
for my signing configs I'm using a file called keystore.properties located under my main folder (I would like to keep it this way in a separate file so I don't upload my keystore signature data to git, so I haven't put the signing config keys like in the current experimental gradle projects).
What am I missing here? How should I write the signing configs to use properties loaded from a file?
As I'm just getting into experimental gradle feel free to give me some examples or info you believe might be useful.
The stuff after create should be in a set of {}'s
android.signingConfigs {
create("mySignature") { // <-- needed
storeFile = file(props['KEYSTORE'])
storePassword = props['KEYSTORE_PASSWD']
keyAlias = props['KEYSTORE_MYAPP']
keyPassword = props['KEYSTORE_MYAPP_PASSWD']
} // <-- needed
}

How do I include `applicationIdSuffix` in some generated resource value?

Imagine this setup:
android {
buildTypes {
debug {
applicationIdSuffix ".debug"
}
}
productFlavors {
foo {
applicationId defaultConfig.applicationId + '.foo'
}
}
}
How can I set up a dynamic string value such as
resValue "string", "package_name", applicationId
so that it includes the applicationIdSuffix for debug builds?
If I add this to defaultConfig, its my defaultConfig's applicationId that is set. If I add this to the flavor configuration, it is missing the applicationIdSuffix (this is null at this level).
Any hints?
The cool part about applicationIdSuffix is that you can use it in flavors as well as in build types. Check this out:
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "dev.bmax.suffixtext"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
applicationIdSuffix '.debug'
}
}
productFlavors {
prod {
applicationIdSuffix '.prod'
}
mock {
applicationIdSuffix '.mock'
}
}
}
Now, when I build my 'prodDebug' variant the final application ID is 'dev.bmax.suffixtext.prod.debug', which is what you want if I understand your question correctly.
EDIT
You can access the variant's name in a Gradle task like this:
applicationVariants.all { variant ->
// Use 'variant.name'
}
Gradle Android Plugin version 0.14.3 added support of the variant specific BuildConfigField/resValue:
applicationVariants.all { variant ->
variant.resValue "string", "name", "value"
}

Gradle BuildConfigFields Syntax

What could be wrong with this syntax? I am getting Gradle DSL method not found:'buildConfigFields()' error.
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.okason.drawingapp"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
def filesAuthorityValue = applicationId + ".files"
//Now you can use ${filesAuthority} in your manifest
manifestPlaceholders = [filesAuthority: filesAuthorityValue]
//Now you can use BuildConfig.FILES_AUTHORITY in our code
buildConfigFields "String", "FILES_AUTHORITY", "\"${filesAuthorityValue}\""
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
you should be using buildConfigField and not buildConfigFields
Change
//Now you can use BuildConfig.FILES_AUTHORITY in our code
buildConfigFields "String", "FILES_AUTHORITY", "\"${filesAuthorityValue}\""
to
//Now you can use BuildConfig.FILES_AUTHORITY in our code
buildConfigField "String", "FILES_AUTHORITY", "\"${filesAuthorityValue}\""
are you sure that buildConfigFields even exits ?

android studio gradle version increment

I'm trying to setup a nice little versioning script in gradle, android studio where the version name increases every time I make a build, while the version code only increases when I make a release build. Is this possible?
What I think would solve it is checking in the if statement below if it is a release or not. But how can I check if it is a release?
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
def versionPropsFile = file('version.properties')
def code
def name
def Properties versionProps
if (versionPropsFile.canRead()) {
versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
code = versionProps['VERSION_CODE'].toInteger() + 1
name = versionProps['VERSION_NAME'].toInteger() + 1
versionProps['VERSION_CODE']=code.toString()
versionProps['VERSION_NAME']=name.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
versionCode code
versionName "1.2." + name
minSdkVersion 14
targetSdkVersion 19
}
} else {
throw new GradleException("Could not read version.properties!")
}
signingConfigs {
debug {
...
}
releaseKey {
...
}
}
buildTypes {
debug {
debuggable true
packageNameSuffix ".debug"
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
signingConfig signingConfigs.debug
}
release {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
signingConfig signingConfigs.releaseKey
}
}
lintOptions {
abortOnError false
}
}
I would like something like:
if (release) code = versionProps['VERSION_CODE'].toInteger() + 1
else code = versionProps['VERSION_CODE'].toInteger()
Any suggestions?
So after a few hours of trial and error I figured out a way this can be done.
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def value = 0
def runTasks = gradle.startParameter.taskNames
if ('assemble' in runTasks || 'assembleRelease' in runTasks || 'aR' in runTasks) {
value = 1;
}
def code = versionProps['VERSION_CODE'].toInteger() + value
def name = versionProps['VERSION_NAME'].toInteger() + 1
versionProps['VERSION_CODE']=code.toString()
versionProps['VERSION_NAME']=name.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
versionCode code
versionName "1.2." + name
minSdkVersion 14
targetSdkVersion 19
}
} else {
throw new GradleException("Could not read version.properties!")
}
signingConfigs {
debug {
...
}
releaseKey {
...
}
}
buildTypes {
debug {
...
}
release {
...
}
}
lintOptions {
abortOnError false
}
}
So what I'm doing is to check if I'm doing a assebleRelease task or not. If I am I increase the versionCode with +1.
Hope this helps anyone else.

how append date build to versionNameSuffix on gradle

I am using Android Studio and I need to append a suffix to the versionNameSuffix on my Android build.gradle file. I have three different build types and I only need to append the datetime to my "beta" release. My actual file is:
defaultConfig {
versionCode 14
versionName "0.7.5"
minSdkVersion 9
targetSdkVersion 18
}
buildTypes {
beta {
packageNameSuffix ".beta"
versionNameSuffix "-beta"
signingConfig signingConfigs.debug
}
....
}
For testing and automatic deploy, I need to get a final versionName like: 0.7.5-beta-build20131004, 0.7.5-beta-build1380855996 or something like that. Any ideas?
beta {
packageNameSuffix ".beta"
versionNameSuffix "-beta" + "-build" + getDate()
signingConfig signingConfigs.debug
}
def getDate() {
def date = new Date()
def formattedDate = date.format('yyyyMMddHHmmss')
return formattedDate
}
Condensed:
def getDate() {
return new Date().format('yyyyMMddHHmmss')
}
You can define in your build.gradle custom functions and variables.
def versionMajor = 3
def buildTime() {
def df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'") // you can change it
df.setTimeZone(TimeZone.getTimeZone("UTC"))
return df.format(new Date())
}
Then you can use it:
android {
defaultConfig {
versionName "${versionMajor}-beta-build-${buildTime()}"
}
}
or if you want to add it in you versionNameSuffix
beta {
versionNameSuffix "-beta-build-${buildTime()}"
}
Also, do not forget to add import as Gradle first line:
import java.text.SimpleDateFormat;
...
for simple one row solution define this property above android section
final BUILD_DATE = new Date().format('yyyy_MM_dd_HHmm')
and then
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId APPLICATION_ID
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.compileSdkVersion
versionName GIT_TAG_NAME
versionCode GIT_COMMIT_COUNT
setProperty("archivesBaseName",`enter code here` "com-appname-$BUILD_DATE-$versionName")
}
}
I'm not familiar with Android Studio, but I'll assume Gradle behaves as it normally does. Adding something like this to your build project configuration should do the trick:
allProjects {
gradle.taskGraph.whenReady { taskGraph ->
versionNameSuffix += '-build' + // Java/Groovy code to produce the timestamp formatted the way you want
}
}
This is for Kotlin DSL (build.gradle.kts):
// At the top of the file
import java.time.LocalDate
import java.time.format.DateTimeFormatter.*
// ...
android {
buildTypes {
getByName("debug") { // OR simply debug { in newer versions of Android Gradle Plugin (AGP)
val date = LocalDate.now().toString()
// OR val date = LocalDate.now().format(ISO_LOCAL_DATE)
// OR val date = LocalDate.now().format(ofPattern("yyyy-MM-dd"))
versionNameSuffix = date
}
}
}
You could also extract the date creation to a function:
android {
buildTypes {
getByName("debug") {
versionNameSuffix = generateDate()
}
}
}
fun generateDate() = LocalDate.now().toString()
// OR fun generateDate() = LocalDate.now().format(ISO_LOCAL_DATE)
// OR fun generateDate() = LocalDate.now().format(ofPattern("yyyy-MM-dd"))
You can test
task timenow {
println(new Date().getTime())
}
Run gradle: gradle timenow
See details. Place it on the top-level build
ext {
configuration = [
appName : "vBulletin",
applicationId : "com.vbulletin",
minSdkVersion : 14,
targetSdkVersion : 19,
compileSdkVersion: 19,
versionCode : 6,
versionName : "1.3.6",
buildToolsVersion: "25.0.0",
]
}
task createBrand {
appConfig.applicationId = appConfig.applicationId + ".${brand}"
appConfig.versionCode = new Date().getTime()
appConfig.versionName = version
}

Categories

Resources