Android instrumentation tests - "Unable to find instrumentation info for: ComponentInfo" - android

I'm trying to run instrumentation tests on Android ( or Espresso tests for that matter ). The error that I'm getting both from Android Studio and console is:
Tests on Nexus_5X_API_23_2(AVD) - 6.0 failed: Unable to find instrumentation info for:
ComponentInfo{com.android.example.country1.demo.debug.test/android.support.test.runner.AndroidJUnitRunner}
com.android.builder.testing.ConnectedDevice > No tests found.[Nexus_5X_API_23_2(AVD) - 6.0] FAILED
No tests found. This usually means that your test classes are not in the form that your test runner expects (e.g. don't inherit from TestCase or lack #Test annotations).
Here is my build.gradle:
buildscript {
repositories {
jcenter()
}
}
apply plugin: 'com.android.application'
android {
signingConfigs {
release
}
compileSdkVersion 23
buildToolsVersion '24.0.0rc3'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
defaultConfig {
versionName "1"
versionCode 1
minSdkVersion 14
targetSdkVersion 23
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
testProguardFile 'proguard-test-rules.pro'
}
buildTypes {
debug {
debuggable true
minifyEnabled true
applicationIdSuffix ".debug"
versionNameSuffix ".debug"
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules-debug.pro'
}
release {
minifyEnabled true // this is a default setting
useProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
flavorDimensions "version", "country"
productFlavors {
country1 {
dimension "country1"
applicationId "com.android.example.country1"
proguardFile 'src/country1/proguard-country1.pro'
}
country2 {
dimension "country2"
applicationId "com.android.example.country2"
proguardFile 'src/country2/proguard-country2.pro'
}
demo {
dimension "version"
}
prod {
dimension "version"
}
}
applicationVariants.all { variant ->
def flavorString = variant.getVariantData().getVariantConfiguration().getFlavorName()
def mergedFlavour = variant.getVariantData().getVariantConfiguration().getMergedFlavor();
if (flavorString.toLowerCase().contains("democountry1")) {
mergedFlavour.setApplicationId("com.android.example.country1.demo")
mergedFlavour.versionName = android.defaultConfig.versionName + ".country1.demo";
...
}
if (flavorString.toLowerCase().contains("prodcountry1")) {
mergedFlavour.setApplicationId("com.android.example.country1")
mergedFlavour.versionName = android.defaultConfig.versionName + ".country1";
...
}
if (flavorString.toLowerCase().contains("democountry2")) {
mergedFlavour.setApplicationId("com.android.example.country2.demo")
mergedFlavour.versionName = android.defaultConfig.versionName + ".country2.demo";
...
}
if (flavorString.toLowerCase().contains("prodcountry2")) {
mergedFlavour.setApplicationId("com.android.example.country2")
mergedFlavour.versionName = android.defaultConfig.versionName + ".country2";
...
}
}
dexOptions {
incremental true
preDexLibraries false
javaMaxHeapSize "4G"
}
}
def props = new Properties()
if (rootProject.file("release.properties").exists()) {
props.load(new FileInputStream(rootProject.file("release.properties")))
android.signingConfigs.release.storeFile rootProject.file(props.keyStore)
android.signingConfigs.release.storePassword props.storePassword
android.signingConfigs.release.keyAlias props.keyAlias
android.signingConfigs.release.keyPassword props.keyPassword
} else {
android.signingConfigs.release.storePassword = 'storePassword'
android.signingConfigs.release.keyAlias = 'keyAlias'
android.signingConfigs.release.keyPassword = 'keyPassword'
}
dependencies {
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:support-v4:23.3.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-jackson:2.0.2'
...
testCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.squareup.retrofit2:retrofit-mock:2.0.2'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'
androidTestCompile 'com.squareup.spoon:spoon-client:1.5.1'
//Version resolutins
androidTestCompile 'com.google.code.findbugs:jsr305:3.0.0'
androidTestCompile 'com.android.support:support-annotations:23.3.0'
}
Note: I know there are a lot of similar questions but after a couple of days of searching and trying solutions I have not found something that works for me.
UPDATE :
Instrumentation test case:
public class RegulatorRestApiAdapterTest extends InstrumentationTestCase {
private MockRetrofit mockRetrofit;
private Retrofit retrofit;
#Override
public void setUp() throws Exception {
retrofit = new Retrofit.Builder().baseUrl("http://test.com")
.client(new OkHttpClient())
.addConverterFactory(JacksonConverterFactory.create())
.build();
NetworkBehavior behavior = NetworkBehavior.create();
mockRetrofit = new MockRetrofit.Builder(retrofit)
.networkBehavior(behavior)
.build();
}
#SmallTest
public void testEcho() throws Exception {
BehaviorDelegate<BackendRestApi> delegate = mockRetrofit.create(BackendRestApi.class);
RegulatorRestApi mockBackendRestApi = new MockBackendRestApi(delegate);
Echo echo = new Echo();
echo.setEchoRequest("EchoString");
//Actual Test
Call<Echo> call = mockBackendRestApi .echo(echo);
Response<Echo> echoResponse = call.execute();
//Asserting response
Assert.assertTrue(echoResponse.isSuccessful());
Assert.assertEquals("EchoString", echoResponse.body().getEchoResponse());
}
}
Espresso test:
#RunWith(AndroidJUnit4.class)
#LargeTest
public class EspressoTest {
#Rule
public ActivityTestRule<LoginActivity> mActivityRule =
new ActivityTestRule<>(LoginActivity.class);
#Test
public void findViewPerformActionAndCheckAssertion() {
// Find Button and Click on it
onView(withId(R.id.numpad_ok)).perform(click());
// Find TextView and verify the correct text that is displayed
onView(withId(R.id.text_view_rocks)).check(matches(withText(
mActivityRule.getActivity().getString(R.string.android_testing_rocks))));
}
}
Both tests fail with the same error and code of neither reaches execution. I'm using Android version 6 and successfully execute Instrumentation and Espresso test examples from the Internet on the same emulator.

I managed to finally resolve it. It might be useful to someone else so I'm posting here.
The way that I was setting application ID was interfering with test application. Although in Android Studio it looked like it was installing application with correct package name when I checked on the device itself the test application ID was lacking ".demo" from "version" flavor dimension.
I made use of the newly introduced ( for flavors )
applicationIdSuffix = ".demo"
Source : http://android-developers.blogspot.bg/2015/12/leveraging-product-flavors-in-android.html
Here is the modified section of my build.gradle:
defaultConfig {
applicationId "com.example"
versionName "1"
versionCode 1
minSdkVersion 14
targetSdkVersion 23
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
testProguardFile 'proguard-test-rules.pro'
}
buildTypes {
debug {
debuggable true
minifyEnabled true
applicationIdSuffix ".debug"
versionNameSuffix ".debug"
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules-debug.pro'
}
release {
minifyEnabled true // this is a default setting
useProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
flavorDimensions "country", "version"
productFlavors {
country1 {
dimension "country1"
applicationIdSuffix = ".country1"
proguardFile 'src/country1/proguard-country1.pro'
}
country2 {
dimension "country2"
applicationIdSuffix = ".country2"
proguardFile 'src/country2/proguard-country2.pro'
}
demo {
dimension "version"
applicationIdSuffix = ".demo"
}
prod {
dimension "version"
}
}
So far I don't think
versionNameSuffix
is usable with flavors so the code below remains.
applicationVariants.all { variant ->
def flavorString = variant.getVariantData().getVariantConfiguration().getFlavorName()
def mergedFlavour = variant.getVariantData().getVariantConfiguration().getMergedFlavor();
if (flavorString.toLowerCase().contains("country1demo")) {
mergedFlavour.versionName = android.defaultConfig.versionName + ".country1.demo";
...
}
if (flavorString.toLowerCase().contains("country1prod")) {
mergedFlavour.versionName = android.defaultConfig.versionName + ".country1";
...
}
if (flavorString.toLowerCase().contains("country2demo")) {
mergedFlavour.versionName = android.defaultConfig.versionName + ".country2.demo";
...
}
if (flavorString.toLowerCase().contains("country2prod")) {
mergedFlavour.versionName = android.defaultConfig.versionName + ".country2";
...
}
}

Related

I have a problem loading widgets in android studio

I do not know why this problem happened I opened my android studio and it does not load the view of my RecyclerView and some other widgets, since I cleaned the cache also used the Rebuild Project but the problem persists, I would appreciate your support
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:scrollbarStyle="outsideOverlay"
android:scrollbarThumbVertical="#android:color/transparent"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:listitem="#layout/item_list_specialties_list"
tools:itemCount="6"
tools:layoutManager="android.support.v7.widget.LinearLayoutManager"
tools:spanCount="1" />
</RelativeLayout>
here is the buildgradle
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply from: "$rootProject.rootDir/app/config.gradle" //Compile Play Store
//apply from: "$rootProject.rootDir/app/config-share-fabric.gradle" //Compile Fabric
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file("keystore.properties")
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
def serverProperties = new Properties()
def serverPropertiesFile = rootProject.file("server.properties")
serverProperties.load(new FileInputStream(serverPropertiesFile))
def configuration = ext.configuration
def configurationUser = ext.configurationUser
def configurationSpecialist = ext.configurationSpecialist
def configurationSeller = ext.configurationSeller
android {
compileSdkVersion configuration.compileSdk
buildToolsVersion configuration.buildTools
defaultConfig {
applicationId configuration.applicationId
minSdkVersion configuration.minimumSdk
targetSdkVersion configuration.targetSdk
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
testHandleProfiling true
testFunctionalTest true
multiDexEnabled true
resConfigs("es", "en")
manifestPlaceholders = [
projectName : configuration.projectName,
fabricApiKey: "17fdb5821b7ac5a50e3250fb679a180d9ab54889"
]
resValue("string", "project_name", "\"${configuration.projectName}\"")
// Used by Room, to test migrations
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
}
//See https://stackoverflow.com/a/36931232
/*sourceSets {
main {
res.srcDirs = [
'src/main/res',
'src/main/res/drawable',
'src/main/res/drawable/splash',
'src/main/res/drawable/selectors'
]
}
}*/
signingConfigs {
debug {
keyAlias keystoreProperties['keyAliasDebug']
keyPassword keystoreProperties['keyPasswordDebug']
storeFile file(keystoreProperties['storeFileDebug'])
storePassword keystoreProperties['storePasswordDebug']
}
configReleaseUser {
keyAlias keystoreProperties['keyAliasUser']
keyPassword keystoreProperties['keyPasswordUser']
storeFile file(keystoreProperties['storeFileUser'])
storePassword keystoreProperties['storePasswordUser']
}
configReleaseSpecialist {
keyAlias keystoreProperties['keyAliasSpecialist']
keyPassword keystoreProperties['keyPasswordSpecialist']
storeFile file(keystoreProperties['storeFileSpecialist'])
storePassword keystoreProperties['storePasswordSpecialist']
}
configReleaseSeller {
keyAlias keystoreProperties['keyAliasSeller']
keyPassword keystoreProperties['keyPasswordSeller']
storeFile file(keystoreProperties['storeFileSeller'])
storePassword keystoreProperties['storePasswordSeller']
}
}
flavorDimensions "app", "server"
productFlavors {
user {
dimension "app"
applicationId configurationUser.applicationId
versionCode configurationUser.versionCode
versionName "${configurationUser.versionMajor}.${configurationUser.versionMinor}" +
".${configurationUser.versionPath}-${configurationUser.versionClasifier}"
proguardFile 'user-proguard-rules.pro'
testApplicationId "pe.com.linkup.android.test.user"
}
specialist {
dimension "app"
applicationId configurationSpecialist.applicationId
versionCode configurationSpecialist.versionCode
versionName "${configurationSpecialist.versionMajor}.${configurationSpecialist.versionMinor}" +
".${configurationSpecialist.versionPath}-${configurationSpecialist.versionClasifier}"
proguardFile 'specialist-proguard-rules.pro'
testApplicationId "pe.com.linkup.android.test.specialist"
}
seller {
dimension "app"
applicationId configurationSeller.applicationId
versionCode configurationSeller.versionCode
versionName "${configurationSeller.versionMajor}.${configurationSeller.versionMinor}" +
".${configurationSeller.versionPath}-${configurationSeller.versionClasifier}"
proguardFile 'seller-proguard-rules.pro'
testApplicationId "pe.com.linkup.android.test.seller"
}
//Desarrollo Local
local {
dimension "server"
applicationIdSuffix ".local"
}
//Desployment Fabric
dev {
dimension "server"
applicationIdSuffix ".dev"
}
//Desployment PlayStore - Testing
staging {
dimension "server"
//applicationIdSuffix ".staging"
}
//Desployment PlayStore - Production
production {
dimension "server"
}
}
// Configura específicamente cada Flavor
productFlavors.all { flavor ->
switch (flavor.name) {
case "user":
flavor.manifestPlaceholders.put("appName", configurationUser.appName)
flavor.resValue("string", "app_name", "\"${configurationUser.appName}\"")
break
case "specialist":
flavor.manifestPlaceholders.put("appName", configurationSpecialist.appName)
flavor.resValue("string", "app_name", "\"${configurationSpecialist.appName}\"")
break
case "seller":
flavor.manifestPlaceholders.put("appName", configurationSeller.appName)
flavor.resValue("string", "app_name", "\"${configurationSeller.appName}\"")
break
case "local":
flavor.buildConfigField("String", "BASE_URL", "\"${serverProperties['baseUrlLocal']}\"")
flavor.buildConfigField("String", "CLIENT_ID", "\"${serverProperties['clientIdLocal']}\"")
flavor.buildConfigField("String", "CLIENT_SECRET", "\"${serverProperties['clientSecretLocal']}\"")
flavor.buildConfigField("String", "GRANT_TYPE", "\"${serverProperties['grantTypeLocal']}\"")
break
case "dev":
flavor.buildConfigField("String", "BASE_URL", "\"${serverProperties['baseUrlDev']}\"")
flavor.buildConfigField("String", "CLIENT_ID", "\"${serverProperties['clientIdDev']}\"")
flavor.buildConfigField("String", "CLIENT_SECRET", "\"${serverProperties['clientSecretDev']}\"")
flavor.buildConfigField("String", "GRANT_TYPE", "\"${serverProperties['grantTypeDev']}\"")
break
case "staging":
flavor.buildConfigField("String", "BASE_URL", "\"${serverProperties['baseUrlStaging']}\"")
flavor.buildConfigField("String", "CLIENT_ID", "\"${serverProperties['clientIdStaging']}\"")
flavor.buildConfigField("String", "CLIENT_SECRET", "\"${serverProperties['clientSecretStaging']}\"")
flavor.buildConfigField("String", "GRANT_TYPE", "\"${serverProperties['grantTypeStaging']}\"")
break
case "production":
flavor.buildConfigField("String", "BASE_URL", "\"${serverProperties['baseUrlProduction']}\"")
flavor.buildConfigField("String", "CLIENT_ID", "\"${serverProperties['clientIdProduction']}\"")
flavor.buildConfigField("String", "CLIENT_SECRET", "\"${serverProperties['clientSecretProduction']}\"")
flavor.buildConfigField("String", "GRANT_TYPE", "\"${serverProperties['grantTypeProduction']}\"")
break
default:
break
}
}
// Configura las variantes merged. Ejm: applicationId ya viene unido con el applicationIdSuffix
applicationVariants.all { variant ->
def name = variant.name
if (name.contains("Local")) {
def filesAuthorityValue = variant.applicationId + ".fileProvider"
variant.mergedFlavor.manifestPlaceholders.put("filesAuthority", filesAuthorityValue)
variant.buildConfigField("String", "FILES_AUTHORITY", "\"${filesAuthorityValue}\"")
} else if (name.contains("Dev")) {
def filesAuthorityValue = variant.applicationId + ".fileProvider"
variant.mergedFlavor.manifestPlaceholders.put("filesAuthority", filesAuthorityValue)
variant.buildConfigField("String", "FILES_AUTHORITY", "\"${filesAuthorityValue}\"")
} else if (name.contains("Staging")) {
def filesAuthorityValue = variant.applicationId + ".fileProvider"
variant.mergedFlavor.manifestPlaceholders.put("filesAuthority", filesAuthorityValue)
variant.buildConfigField("String", "FILES_AUTHORITY", "\"${filesAuthorityValue}\"")
} else if (name.contains("Production")) {
def filesAuthorityValue = variant.applicationId + ".fileProvider"
variant.mergedFlavor.manifestPlaceholders.put("filesAuthority", filesAuthorityValue)
variant.buildConfigField("String", "FILES_AUTHORITY", "\"${filesAuthorityValue}\"")
}
}
buildTypes {
debug {
//applicationIdSuffix ".debug"
minifyEnabled false
debuggable true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
productFlavors.user.signingConfig signingConfigs.debug
productFlavors.specialist.signingConfig signingConfigs.debug
productFlavors.seller.signingConfig signingConfigs.debug
buildConfigField "boolean", "LOG", "true"
// disable crashlytics
buildConfigField "boolean", "ENABLE_CRASHLYTICS", "false"
ext.enableCrashlytics = false
}
relebug {
//applicationIdSuffix ".relebug"
minifyEnabled false
debuggable true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "boolean", "LOG", "true"
// disable crashlytics
buildConfigField "boolean", "ENABLE_CRASHLYTICS", "false"
ext.enableCrashlytics = false
matchingFallbacks = ['release']
}
release {
zipAlignEnabled true
minifyEnabled true
shrinkResources true
debuggable false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
productFlavors.user.signingConfig signingConfigs.configReleaseUser
productFlavors.specialist.signingConfig signingConfigs.configReleaseSpecialist
productFlavors.seller.signingConfig signingConfigs.configReleaseSeller
buildConfigField "boolean", "LOG", "false"
// enable crashlytics
buildConfigField "boolean", "ENABLE_CRASHLYTICS", "true"
ext.enableCrashlytics = true
}
}
// Ignora algunas variantes de compilación para su visualización en la BuildVariant
variantFilter { variant ->
def app = variant.getFlavors().get(0).name
def server = variant.flavors.get(1).name
def isRelease = variant.buildType.name.contains('release')
def isRelebug = variant.buildType.name.contains('relebug')
def isDebug = variant.buildType.name.contains('debug')
if (server.contains('local')) {
variant.setIgnore(false)
} else if (server.contains('dev')) {
variant.setIgnore(false)
} else if (server.contains('staging')) {
variant.setIgnore(false)
} else if (server.contains('production')) {
variant.setIgnore(true) //Temporal
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
lintOptions {
abortOnError false
lintConfig file("../lint.xml")
}
dexOptions {
jumboMode true
//incremental true
}
testOptions {
reportDir "$rootDir/test-reports"
resultsDir "$rootDir/test-results"
unitTests {
returnDefaultValues = true
all {
jvmArgs '-XX:MaxPermSize=256m'
if (it.name == 'testDebugUnitTest') {
systemProperty 'debug', 'true'
}
}
}
}
//Renombrar Apk de salida
applicationVariants.all { variant ->
variant.outputs.all { output ->
def projectName = "linkup"
def formattedDate = new Date().format('yyyyMMdd', TimeZone.getTimeZone("UTC"))
def apkName = "${projectName}-${variant.flavorName}-${variant.versionName}-${variant.versionCode}-${formattedDate}-${variant.buildType.name}" + ".apk"
def apkDirectory = "${output.outputFile.parent}/apk/${variant.flavorName}/${variant.buildType.name}"
//outputFileName = new File(apkDirectory, apkName)
outputFileName = apkName
}
}
crashlytics {
enableNdk true
androidNdkOut 'src/main/obj'
androidNdkLibsOut 'src/main/libs'
}
}
repositories {
jcenter()
google()
mavenCentral()
maven { url "https://jitpack.io" }
maven { url 'https://maven.fabric.io/public' }
}
apply from: "$rootProject.rootDir/app/library.gradle"
def library = ext.library
def libraryTest = ext.libraryTest
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation library.support_appcompat
implementation library.support_recyclerview
implementation library.support_v4
implementation library.support_v13
implementation library.support_design
implementation library.support_cardview
implementation library.support_customtabs
implementation library.support_annotations
implementation library.support_vector_drawable
implementation library.support_constraint
implementation library.support_multidex
implementation library.firebase_core
implementation library.firebase_auth
implementation library.firebase_database
implementation library.firebase_storage
implementation library.firebase_messaging
implementation library.firebase_config
implementation library.firebase_invites
implementation library.exoplayer_core
implementation library.exoplayer_ui
implementation library.exoplayer_dash
implementation library.butterknife
annotationProcessor library.butterknife_compiler
implementation library.retrofit2
implementation library.retrofit2_converter_gson
implementation library.logging_interceptor
implementation library.glide
implementation library.joda_time
implementation library.shortcut_badger
implementation library.smiley_rating
//Room
implementation library.room
annotationProcessor library.room_compiler
implementation library.room_assets
//GMS
implementation library.play_services_location
implementation library.play_services_maps
// Crashlytics
implementation(library.crashlytics) {
transitive = true
}
// Crashlytics NDK
implementation(library.crashlytics_ndk) {
transitive = true
}
implementation library.spinner_date_picker
//Testing
testImplementation libraryTest.junit
testImplementation libraryTest.mockito_core
testImplementation libraryTest.robolectric
testImplementation libraryTest.robolectric_shadows
//UI testing
// Espresso dependenciesVersions
androidTestImplementation(libraryTest.expresso_core, {
exclude group: 'com.android.support', module: 'support-annotations'
})
}
configurations.all {
resolutionStrategy.force library.support_annotations
resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.2'
}
//TODO: Pendiente -> https://howards543.ddns.net/gradle-script-with-multi-flavor-resource-management/
task("copyGoogleServicesJson", type: Copy) {
println 'copyGoogleServicesJson'
from('$rootProject.rootDir/app/services/dev/google-services.json')
into("$rootProject.rootDir/app")
include('*.json')
}
//apply from: "$rootProject.rootDir/setup/artifacts.gradle"
apply plugin: 'com.google.gms.google-services'
Just based on the dependencies, these were added correctly and the code did not move, my buildgradle structure it in this way where I use library.gradle to call the libraries by version and this is the specic code of the implementation of the RecyclerView.
ext.versions = [
supportLib : '28.0.0'
]
def version = ext.versions
ext.library = [
support_recyclerview : 'com.android.support:recyclerview-v7:' + version.supportLib
]
Use Fragment with RecyclerView and Activity host for this Fragment.

Proguard not working after update to Google Play Services 11.8.0

After updating Google Play Services to 11.8.0 (from 11.6.2) my builds stop working.
This is what I got:
Unexpected error while computing stack sizes:
Class = [com/google/android/gms/internal/zzao]
Method = [zzf(Ljava/lang/String;)J]
Exception = [java.lang.IllegalArgumentException] (Stack size becomes negative after instruction [23] invokestatic #146 in [com/google/android/gms/internal/zzao.zzf(Ljava/lang/String;)J])
FAILURE: Build failed with an exception.
I'm using Android Studio 3.0.1 with Gradle 4.4.1
My app build.gradle file
buildscript {
repositories {
maven { url "https://maven.fabric.io/public" }
}
dependencies {
classpath "io.fabric.tools:gradle:1.25.1"
}
}
repositories {
maven { url "https://maven.fabric.io/public" }
}
apply plugin: "com.android.application"
apply plugin: "io.fabric"
apply plugin: "let"
apply plugin: "realm-android"
android {
compileSdkVersion project.androidSDKVersion
buildToolsVersion("$androidBuildToolsVersion")
defaultConfig {
versionCode project.versionCode
versionName project.versionName
minSdkVersion project.androidMinSdkVersion
targetSdkVersion project.androidTargetSdkVersion
vectorDrawables.useSupportLibrary = true
resConfigs "pl"
}
buildTypes {
release {
minifyEnabled true
shrinkResources false
crunchPngs false
proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", "proguard-fresco.pro"
signingConfig signingConfigs.release
}
debug {
ext.enableCrashlytics = false
ext.alwaysUpdateBuildId = false
}
}
flavorDimensions "tier", "minApi"
productFlavors {
minApi21 {
minSdkVersion project.androidMinDevSdkVersion
dimension "minApi"
}
minApi16 {
minSdkVersion project.androidMinSdkVersion
dimension "minApi"
}
dev {
multiDexEnabled true
dimension "tier"
}
prod {
multiDexEnabled false
dimension "tier"
}
}
variantFilter { variant ->
def names = variant.flavors*.name
if (names.contains("prod") && names.contains("minApi21")) {
setIgnore(true)
}
}
applicationVariants.all { variant ->
appendVersionNameVersionCode(variant, defaultConfig)
}
lintOptions {
checkReleaseBuilds false
textReport true
textOutput "stdout"
fatal "UnusedResources"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
debugImplementation("com.android.support:multidex:$multidexVersion")
implementation("com.android.support:support-fragment:$androidSupportVersion")
implementation("com.android.support:support-annotations:$androidSupportVersion")
implementation("com.android.support:appcompat-v7:$androidSupportVersion")
implementation("com.android.support:design:$androidSupportVersion")
implementation("com.android.support:recyclerview-v7:$androidSupportVersion")
implementation("com.android.support:cardview-v7:$androidSupportVersion")
implementation("com.android.support:customtabs:$androidSupportVersion")
implementation("com.android.support.constraint:constraint-layout:$constraintLayoutVersion")
implementation("com.android.installreferrer:installreferrer:$installReferrerVersion")
implementation("com.google.android.gms:play-services-analytics:$playServicesVersion")
implementation("com.google.android.gms:play-services-location:$playServicesVersion")
implementation("com.google.android.gms:play-services-ads:$playServicesVersion")
implementation("com.google.android.gms:play-services-auth:$playServicesVersion")
implementation("com.google.firebase:firebase-core:$playServicesVersion")
implementation("com.google.firebase:firebase-messaging:$playServicesVersion")
implementation("com.google.firebase:firebase-config:$playServicesVersion")
implementation("com.google.firebase:firebase-auth:$playServicesVersion")
implementation("com.google.firebase:firebase-invites:$playServicesVersion")
(...) // I had removed other dependencies from the list
}
def appendVersionNameVersionCode(variant, defaultConfig) {
variant.outputs.all { output ->
def versionCode = android.defaultConfig.versionCode
output.versionCodeOverride = versionCode
outputFileName = "${rootProject.name}-${variant.name}-${variant.versionName}-${versionCode}.apk"
}
}
apply plugin: "com.google.gms.google-services"
You don't need to disable optimization entirely, just optimization on the problem class. I had the same issue and got around it by adding the following to the proguard-rules.pro file:
-keep class com.google.android.gms.internal.** { *; }
I have a similar issue. As suggested in this SO thread you just need to add these lines in your build.gradle file :
...
release {
debuggable false
useProguard true
...
}
...
I also had to remove the pro guard optimization by replacing :
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
by
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

Generate different gradle constants for different flavours and different build types - Android

The requirement is pretty simple. But i am not finding any way to do that.
I have an app with two flavours : original and black.
productFlavors {
original {
}
black {
applicationIdSuffix ".black"
versionNameSuffix "-black"
}
}
Each flavour is having two build types : debug and release
I am generating a runtime gradle constant "APP_INFO" for different build types.
buildTypes {
debug {
buildConfigField "String", "APPINFO", "DEBUG"
signingConfig signingConfigs.debug
}
release {
buildConfigField "String", "APPINFO", "RELEASE"
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
What i am getting right now for BuildConfig.APPINFO
flavour : original , buildType : debug. APPINFO "DEBUG"
flavour : original , buildType : release. APPINFO "RELEASE"
flavour : black , buildType : debug. APPINFO "DEBUG"
flavour : black , buildType : release. APPINFO "RELEASE"
I need required value of APPINFO for given flavour and BuildTypes :
flavour : original , buildType : debug. APPINFO should be "DEBUG_ORIGINAL"
flavour : original , buildType : release. APPINFO should be "RELEASE_ORIGINAL"
flavour : black , buildType : debug. APPINFO should be "DEBUG_BLACK"
flavour : black , buildType : release. APPINFO should be "RELEASE_BLACK"
My Gradle File is as below :
apply plugin: 'com.android.application'
android {
signingConfigs {
release {
}
debug {
}
}
compileSdkVersion 27
buildToolsVersion '27.0.2'
defaultConfig {
applicationId "com.lifeyup.app.xyz"
minSdkVersion 19
targetSdkVersion 27
versionCode 7
versionName "1.0.7"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
productFlavors {
original {
}
black {
applicationIdSuffix ".black"
versionNameSuffix "-black"
}
}
buildTypes {
debug {
original {
buildConfigField "String", "APPINFO", "DEBUG_ORIGINAL"
signingConfig signingConfigs.debug
}
black{
buildConfigField "String", "APPINFO", "DEBUG_BLACK"
signingConfig signingConfigs.debug
}
}
release {
original {
buildConfigField "String", "APPINFO", "RELEASE_ORIGINAL"
signingConfig signingConfigs.debug
}
release {
buildConfigField "String", "APPINFO", "RELEASE_BLACK"
signingConfig signingConfigs.release
}
}
}
apply plugin: 'io.fabric'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-
core:2.2.2',
{
exclude group: 'com.android.support', module: 'support-annotations'
})
compile('com.crashlytics.sdk.android:crashlytics:2.6.8#aar') {
transitive = true;
}
compile 'com.google.code.gson:gson:2.7'
compile 'com.android.support:appcompat-v7:27.0.2'
compile 'com.google.firebase:firebase-database:11.8.0'
compile 'com.android.support:recyclerview-v7:27.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support:cardview-v7:27.0.2'
compile 'com.android.support:design:27.0.2'
compile 'com.google.firebase:firebase-messaging:11.8.0'
compile 'org.jsoup:jsoup:1.10.3'
compile 'com.facebook.stetho:stetho:1.5.0'
compile 'com.google.android.gms:play-services-ads:11.8.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-storage:11.8.0'
compile 'com.google.firebase:firebase-config:11.8.0'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
Thanks in advance.
You can use BuildConfig.DEBUG which returns a boolean to check if build is debug or release and for checking the build flavor just check BuildConfig.FLAVOR
for example :
For original flavor and debug build set APPINFO as
if(BuildConfig.DEBUG && BuildConfig.FLAVOR.equalsIgnoreCase("original")) {
APPINFO = "DEBUG_ORIGINAL"
} else {
// other cases
}
try replacing below code for build types section:
buildTypes {
debug {
signingConfig signingConfigs.debug
productFlavors {
original {
buildConfigField "String", "APPINFO", "DEBUG_ORIGINAL"
}
black {
buildConfigField "String", "APPINFO", "DEBUG_BLACK"
}
}
}
release {
signingConfig signingConfigs.debug
productFlavors {
original {
buildConfigField "String", "APPINFO", "RELEASE_ORIGINAL"
}
black {
buildConfigField "String", "APPINFO", "RELEASE_BLACK"
}
}
}
}
Then you can try below code also. This will work for you :
debug {
productFlavors {
original {
buildConfigField "String", "APPINFO", "DEBUG_ORIGINAL"
}
black {
buildConfigField "String", "APPINFO", "DEBUG_BLACK"
}
}
}
release {
//// similarly for release here
}

Can't run in debug mode

I am trying to launch my android application in debug mode, but everytime I check BuildConfig.DEBUG it says it is false. Even further, a buildconfigField defined in my buildtypes does not even show up in BuildConfig.
Here is my gradle file:
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.22.0'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
repositories {
maven {
url 'https://maven.fabric.io/public'
}
}
def versionMajor = 1
def versionMinor = 2
def versionPatch = 41
def versionBuild = 0 // bump for dogfood builds, public betas, etc.
android {
compileOptions.encoding = 'ISO-8859-1'
compileSdkVersion 21
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.name"
minSdkVersion 17
targetSdkVersion 21
buildConfigField 'Boolean', 'enableCrashlytics', 'false'
multiDexEnabled true
versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild
versionName "${versionMajor}.${versionMinor}.${versionPatch}.${versionBuild}"
}
signingConfigs {
release {
// release stuff
}
}
buildTypes {
android {
release {
debuggable false
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
buildConfigField 'Boolean', 'enableCrashlytics', 'true'
}
debug {
buildConfigField 'Boolean', 'enableCrashlytics', 'false'
debuggable true
minifyEnabled false
applicationIdSuffix ".debug"
}
}
}
sourceSets {
main {
res.srcDirs = ['src/main/res', 'src/main/res/xml']
}
}
dexOptions {
incremental true
javaMaxHeapSize "2048M"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
lintOptions {
checkReleaseBuilds false
abortOnError false
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.1.1'
// ... some other libs
compile('com.crashlytics.sdk.android:crashlytics:2.6.6#aar') {
transitive = true;
}
}
So in Android Studio I chooseBuild Variant "debug" for my app, but when I hit a breakpoint in the application and check the values of BuildConfig, the filed enableCrashlytics cant be resolved and the value of BuildConfig.BUILD_TYPE is "release".
What am I doing wrong?
This may happen if the code is in a library, there are multiple BuildConfig classes in a project, one per module, and only the main app one will be updated as expected.
If you want to have a proper BuildConfig.BUILD_TYPE across the app, you'd need to have debug/release build types on all your modules' gradle files, and trickle down the selected build-type from the main gradle file to the dependencies.

Android Studio Error JUNIT4 !!! JUnit version 3.8 or later expected:

I'm doing Android project (in Android Studio), with a little SDK inside that is pure java.
So What I want is to do test from JUnit4.
And I configured the Gradlle File in this way:
apply plugin: 'android'
android {
compileSdkVersion "Google Inc.:Google APIs:19"
buildToolsVersion "19.0.1"
lintOptions{
checkReleaseBuilds false
}
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 28
versionName "4.0.5"
}
signingConfigs {
debug {
}
release {
}
}
buildTypes {
debug{
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
debuggable true
buildConfigField "boolean", "LOG_ENABLED", "true"
signingConfig signingConfigs.debug
}
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
debuggable false
buildConfigField "boolean", "LOG_ENABLED", "false"
signingConfig signingConfigs.release
}
}
productFlavors{
develFlavor{
}
testFlavor{
}
trainingFlavor{
}
preFlavor{
}
proFlavor{
}
}
}
if (project.hasProperty('storePassword')) {
android.signingConfigs.release.storePassword = storePassword
}
if (project.hasProperty('keyAlias')) {
android.signingConfigs.release.keyAlias = keyAlias
}
if (project.hasProperty('keyPassword')) {
android.signingConfigs.release.keyPassword = keyPassword
}
//testing
sourceSets {
unitTest {
java.srcDir file('test')
resources.srcDir file('test/resources')
}
}
configurations {
unitTestCompile.extendsFrom runtime
unitTestRuntime.extendsFrom unitTestCompile
}
task unitTest(type:Test, dependsOn: assemble) {
description = "run unit tests"
testClassesDir = project.sourceSets.unitTest.output.classesDir
classpath = project.sourceSets.unitTest.runtimeClasspath
}
build.dependsOn unitTest
dependencies {
compile files('libs/junit-4.11-sources.jar')
unitTestCompile 'junit:junit:4.11'
unitTestCompile files("$project.buildDir/classes/debug")
compile 'com.google.code.gson:gson:+'
compile 'com.android.support:appcompat-v7:+'
compile files('libs/libGoogleAnalyticsServices.jar')
compile files('libs/sbc_mapslib.jar')
compile files('libs/t21c2dm-lib-v1.0.jar')
}
Then I do a simply test case to see if junitis working. But when I run it, this error is promted.
!!! JUnit version 3.8 or later expected:
I saw in some other question that the solutions was, change dependences of Junit4.jar to be in first position, but it doesn't work to
If you test Android specific behaviour, that means if you need to run the test on the device (hardware or Emulator), you cannot use JUnit 4, because it's not built in in that version. You need to use JUnit 3 (I know that's cumbersome).
If you have some tests where you don't need a running Android, you can use every version you like (as you do with standard JUnit tests).

Categories

Resources