Android Studio gradle apk and run out of sync - android-studio

I am using Android Studio and I have the following build.gradle file.
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
dexOptions {
javaMaxHeapSize "4g"
preDexLibraries = false
}
defaultConfig {
applicationId "com.domain.myapp"
minSdkVersion 17
targetSdkVersion 25
versionName "1.0"
versionCode 2
versionNameSuffix = ".alpha1"
def date = new Date().format('yyyyMMddHHmmss')
if (versionNameSuffix.equals("")) {
setProperty("archivesBaseName", "myapp.$versionName.$versionCode")
} else {
setProperty("archivesBaseName", "myapp.$versionName.$versionCode$versionNameSuffix." + date)
}
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
buildConfigField 'boolean', 'IS_DEBUG', 'false'
buildConfigField 'String', 'BUILD_DATE', '\"' + date + '\"'
buildConfigField 'String', 'VERSION_STRING', '\"' + "$versionName.$versionCode$versionNameSuffix" + '\"'
resValue "string", "BUILD_DATE", date
resValue "string", "VERSION", "$versionName.$versionCode$versionNameSuffix"
}
buildTypes {
release {
buildConfigField 'boolean', 'IS_DEBUG', 'false'
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
applicationVariants.all { variant ->
variant.outputs.each { output ->
def newName = output.outputFile.name
newName = newName.replace("-release", "")
output.outputFile = new File(output.outputFile.parent, newName)
}
}
}
debug {
buildConfigField 'boolean', 'IS_DEBUG', 'true'
applicationVariants.all { variant ->
variant.outputs.each { output ->
def newName = output.outputFile.name
output.outputFile = new File(output.outputFile.parent, newName)
}
}
}
}
productFlavors {
}
}
Basically when I Build->Rebuild Project or Build->Build APK, I generate an apk file like myapp.1.0.2.alpha1.20170224125933.apk
The last bit on the end is a time-stamp. (20170224125933 => 2017/2/24 12:59:33)
Everything works perfectly when running manually via the apk.
The issue I am having is that when I try to Run->Run myapp through Android Studio, it seems to always look for an earilier time-stamp.
For example, let's say I Rebuild Project and get the file: myapp.1.0.2.alpha1.20170224125933.apk. I make some code changes and want to Run it through Anroid Studio. When I go to Run, it rebuilds the project again (generating myapp.1.0.2.alpha1.20170224130417.apk) and deletes the previous file (myapp.1.0.2.alpha1.20170224125933.apk) as expected, but, tries to install the previous file. I then get an "error while installing apk. File myapp.1.0.2.alpha1.20170224125933.apk not found."
The only solution I've found is to drop the seconds marker (change the Date format to 'yyyyMMddHHmm'), click Tools->Android->Sync Project with Gradle Files, then immediately hit Run. This usually works unless the clock changes minutes during the few seconds this process takes.
I'm thinking I need a Gradle->Task Activitaion or something so that when I click Run, it generates a new apk, and knows to use the recently generated one.
Any ideas?

Related

Gradle build error after updating android studio: NumberFormatException for versionCode

I got an error I had not before:
Execution failed for task ':app:generateDebugBuildConfig'.
> Failed to calculate the value of task ':app:generateDebugBuildConfig' property 'buildConfigPackageName'.
> Failed to query the value of property 'packageName'.
> java.lang.NumberFormatException: For input string: "${versionCode}"
The android studio version is:
Android Studio 4.1.1
Build #AI-201.8743.12.41.6953283, built on November 5, 2020
Runtime version: 1.8.0_242-release-1644-b3-6222593 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
The build.gradle(:app) file contains the following:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt' //< for image visualization with glide
//Serialization
apply plugin: 'kotlinx-serialization'
android {
signingConfigs {
release {
storeFile file('xxxx.jks')
storePassword 'xxxxxxx'
keyPassword 'xxxxxxxx'
keyAlias 'my-app'
}
}
compileSdkVersion propCompileSdkVersion
buildToolsVersion propBuildToolsVersion
defaultConfig {
applicationId "com.user.myapp"
minSdkVersion propMinSdkVersion
targetSdkVersion propTargetSdkVersion
versionCode 3
versionName "2.0-beta.26"
manifestPlaceholders = [versionCode:"3", versionName:"2.0-beta.26"]
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
applicationIdSuffix ".debug"
debuggable true
resValue "string", "app_name", "myapp-dev"
}
optimizedDebug {
initWith debug
minifyEnabled false
applicationIdSuffix ".optimizedDebug"
debuggable false
resValue "string", "app_name", "myapp-optimized-dev"
}
debugProd {
initWith debug
minifyEnabled false
applicationIdSuffix ".debugProd"
debuggable true
resValue "string", "app_name", "myapp-logs-in-prod"
}
release {
minifyEnabled false
resValue "string", "app_name", "myapp"
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.resValue "string", 'images_file_path', "Android/data/\"${applicationId}\"/files/Pictures"
}
/* Necessary to have Parcelable / #Parcelize functionalities */
androidExtensions {
experimental = true
}
lintOptions {
checkReleaseBuilds false
abortOnError true
}
}
dependencies {
...
}
repositories {
mavenCentral()
}
I have invalidated the caches and restarted several times, nothing changes.
I would like to pinpoint exactly what happens, to at least be able to understand what causes gradle to be confused.
Can anyone point me to a step by step run of gradle to find what is the problem ?
I found that in the manifest I had the following error annotated by android studio:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.user.myapp"
android:versionCode={$versionCode}
android:versionName={$versionName}
>
...
</manifest>
It looks that in the 4.1.1 release of android studio,
android:versionCode={$versionCode}
is not working anymore.
This post https://commonsware.com/blog/2020/10/14/android-studio-4p1-library-modules-version-code.html says that we should no more use VERSION_CODE and VERSION_NAME.
So I remove them entirely from my code and replaced it with custom buildConfigField gradle variables:
in gradle:
defaultConfig {
...
buildConfigField 'int', 'MYAPP_VERSION_CODE', "3"
buildConfigField 'String', 'MYAPP_VERSION_NAME', "\"2.0-beta.26\""
...
}
in manifest remove the part referencing android:versionXXXX:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.user.myapp"
>
...
</manifest>
in kotlin code to display code and name version:
val versionCode = BuildConfig.MYAPP_VERSION_CODE.toString()
val versionName = BuildConfig.MYAPP_VERSION_NAME
It works nicely after that.

Cannot invoke method multiply() on null object

I'm trying to generate split apk in react-native and getting this error after setting these two properties:
def enableSeparateBuildPerCPUArchitecture = true
def enableProguardInReleaseBuilds = true
This is the error I'm getting:
Cannot invoke method multiply() on null object
Open File
On clicking the open file, it is pointing me to this code:
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
My configurations are like this:
defaultConfig {
applicationId PACKAGE_NAME
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode VERSION_CODE
multiDexEnabled true
versionName MY_VERSION_HERE
ndk {
abiFilters "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a":3, "x85_64":4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
Please help me with this or at least give me a clue why this should be happening.
I ended creating another project, installing all the repository and it worked.
Still, don't know why it was happening in the first place.
you should change "x85_64" -> "x86_64" in the applicationVariants.all setting
Debuging here I added a line:
println abi
before the output.versionCodeOverride line and saw the abi needed. Then, added the abi on line def versionCodes. It ends like:
def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a":3, "x86_64":4]

Android Studio build variant problems

I am having difficulty getting Android Studio to build the right build variant — or even to let me select a build variant at all, sometimes.
Basically I have two different versions of my project a free and a "full" version. Package ids are "com.mycompany.myproj" and "com.mycompany.myprojfree".
Once I've specified "myproj" and "myprojfree" flavors and "release" and "debug" buildtypes, Android Studio produces four variants in the list: myprojDebug, myprojfreeDebug, myprojfreeRelease, and myprojRelease.
Problem is, selecting one of these doesn't reliably select the variant for building, debugging, etc. For instance, I'll select myprojDebug, hit Debug, and myprojfreeDebug will build (as can be seen in the console), and the free version will open on the attached device.
Moreover, sometimes I can't even select one or more of the build variants in the build variant pane. I can click on it, but it doesn't change. But sometimes if I change it to something else first it'll let me go back and change the non-changing one.
I've seen posts referring to similar-sounding problems and have followed all the suggestions — cleaning, rebuilding, deleting .idea, deleting the build folder, Invalidate Caches/Restart, deleting app.iml, etc. — all to no avail.
It may be worth noting that all of this worked fine until yesterday, when I updated from Android Studio 3.1 to 3.4.1.
Here's a simplified version of my app build.gradle:
apply plugin: 'com.android.application'
android {
defaultConfig {
versionCode ...
multiDexEnabled true
vectorDrawables {
useSupportLibrary true
}
minSdkVersion 15
targetSdkVersion 28
}
compileSdkVersion 28
signingConfigs {
myproj {
keyAlias ...
keyPassword ...
storeFile file('...')
storePassword ...
}
myprojfree {
keyAlias ...
keyPassword ...
storeFile file('...')
storePassword ...
}
}
flavorDimensions "tier"
productFlavors {
myproj {
signingConfig signingConfigs.myproj
applicationId 'com.mycompany.myproj'
}
myprojfree {
signingConfig signingConfigs.myprojfree
applicationId 'com.mycompany.myprojfree'
}
}
buildTypes {
release {
debuggable false
buildConfigField "Boolean", "MY_DEBUG_MODE", "false"
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
}
debug {
debuggable true
buildConfigField "Boolean", "MY_DEBUG_MODE", "true"
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
}
configurations {
implementation.exclude group: "org.apache.httpcomponents", module: "httpclient"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
...
}
I'm pretty sure the problem came from a non-synchrony between files and Gradle sync.
So do `File/Sync Project with Gradle Files' after a change of Build Variant.
Then clean project, rebuild and run.

Running debug on older Android 4.4.2 using Android Studio

I am trying to debug on an older Android device (Samsung Tab3 4.4.2). The strange thing is I am getting an error that I do not see when running on my new devices (Android 6+).
When I hit the debug button, a Gradle build is shot off and I get the following error:
06/21 15:55:35: Launching splashActivity
The APK file C:\Users\me\Documents\src\myapp\build\outputs\apk\MyApp\debug\10-MyApp.apk does not exist on disk.
Error while Installing APK
The file is not there, but is not there when I run against the newer versions, which successfully debug. Is Android Studio doing something different due to the older version? Do I need to make some sort of Gradle adjustment?
My Gradle build appends a version to the front of the APK, could that be the problem? Here is the Gradle file (I have removed the flavors, have a ton of them):
buildscript {
ext.kotlin_version = '1.1.1'
}
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.myapp.app"
minSdkVersion 15
targetSdkVersion 23
versionCode 10
versionName "1.1.10"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7 }
}
aaptOptions {
cruncherEnabled = false
}
dexOptions {
javaMaxHeapSize "4g"
jumboMode true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
productFlavors.whenObjectAdded { flavor ->
flavor.ext.set('directoryPath', '')
flavor.ext.set('apkName', '')
}
flavorDimensions "default"
productFlavors {
MyApp {
signingConfig signingConfigs.config
directoryPath = 'myapp'
}
Flavor1 {
applicationId 'com.flavor1.flavor'
signingConfig signingConfigs.config
directoryPath = 'flavor1'
}
}
applicationVariants.all { variant ->
variant.outputs.all {
def apkName = variant.productFlavors[0].apkName
def flavor = variant.productFlavors[0].name
if (apkName != '')
flavor = apkName;
//add here your logic to customize the name of the apk
outputFileName = "${variant.versionCode}-${flavor}.apk"
}
variant.assemble.doLast { assemble ->
//copy the apk in another directory, add here your
//logic to customize the destination folder
copy {
from variant.outputs*.outputFile
into "C:/AndroidBuilds/MyApp.Build/${variant.productFlavors[0].directoryPath}"
}
//if you don't want to delete the file after copying it comment the line below
delete variant.outputs*.outputFile
}
}
}
I have removed dependencies and such to make it smaller, and changed names to protect the innocent.
Doh, it was the following line of code in Gradle, that was deleting the variant. Apparently it is needed to run on older versions of Android:
//if you don't want to delete the file after copying it comment the line below
// delete variant.outputs*.outputFile

Android studio 3: Could not find the AndroidManifest.xml file

after migrating to Android studio 3 I'm unable to compile as I' have folowing errors:
Error:Could not find the AndroidManifest.xml file, using generation
folder
[/home/salacr/git/Evotech/app/build/generated/source/apt/debug])
Error:Parceler: Code generation did not complete successfully. For
more details add the compiler argument -AparcelerStacktrace
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
It might be connected with usage of android anotation my app/build.gradle looks like this:
apply plugin: 'com.android.application'
apply plugin: 'realm-android'
def AAVersion = '4.3.1'
def parcelerVersion = '1.1.9'
android {
compileSdkVersion 26
buildToolsVersion '26.0.1'
defaultConfig {
applicationId "com.my.app"
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"
multiDexEnabled true
}
signingConfigs {
release {
storeFile file("******")
storePassword "******"
keyAlias "******"
keyPassword "******"
}
}
buildTypes {
release {
minifyEnabled false
signingConfig signingConfigs.release
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
splits {
abi {
enable true // enable ABI split feature to create one APK per ABI
universalApk true //generate an additional APK that targets all the ABIs
}
}
/*
// map for the version code
project.ext.versionCodes = ['armeabi':1, 'armeabi-v7a':2, 'arm64-v8a':3, 'mips':5, 'mips64':6, 'x86':8, 'x86_64':9]
android.applicationVariants.all { variant ->
// assign different version code for each output
variant.outputs.each { output ->
output.versionCodeOverride =
project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 1000000 + android.defaultConfig.versionCode
}
}
*/
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation "org.parceler:parceler-api:$parcelerVersion"
annotationProcessor "org.parceler:parceler:$parcelerVersion"
annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
implementation "org.androidannotations:androidannotations-api:$AAVersion"
implementation 'com.android.support:appcompat-v7:26.0.1'
implementation 'com.android.support:multidex:1.0.2'
}
I'm unable to find the root cause for this, any suggestions?
I tried diferent graddle versions as well as using different buildToolsVersion tools, but without effect.
Any suggestions?
Thanks!
EDIT 1: I have found out that problem is here:
splits {
abi {
enable true // enable ABI split feature to create one APK per ABI
universalApk true //generate an additional APK that targets all the ABIs
}
}
Without this everything works as expected. IT seams that this config isn't compatible with androidanotations in new Android studio
EDIT 2: There is already issue in androidanotation: https://github.com/androidannotations/androidannotations/issues/2034
I had similar issue and solved my problem when I updated android annotation version from 4.4.0 to 4.5.0.
Add the following code in build.gradle file under defaultConfig
javaCompileOptions {
annotationProcessorOptions {
arguments = [
"androidManifestFile":"$projectDir/src/main/AndroidManifest.xml".toString()
]
}
}
I solved this problem changed graddle version:
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
I had similar issue and solved my problem when I updated android annotation version from 4.4.0 to 4.6.0.

Resources