2

I am creating android project through cordova plugin, but in the android project created, it has the build.gradle with

if (gradle.gradleVersion >= "2.2") {
        dependencies {
            classpath 'com.android.tools.build:gradle:1.0.0+'
        }
    } else if (gradle.gradleVersion >= "2.1") {
        dependencies {
            classpath 'com.android.tools.build:gradle:0.14.0+'
        }
    } else {
        dependencies {
            classpath 'com.android.tools.build:gradle:0.12.0+'
        }
    }

instead of,

classpath 'com.android.tools.build:gradle:2.0.0'

So it gives me the error,

Error:'com.android.build.gradle.BasePlugin' does not implement the Plugin interface.

Why is it happening? How to make it generate according the version of the gradle automatically?

This is my build-extras.gradle,

ext.postBuildExtras = {
    android.buildTypes.debug.applicationIdSuffix = '.debug'
    buildscript {

        repositories {
            jcenter()
            flatDir {
                dirs 'libs'
            }
            maven { url 'https://maven.fabric.io/public' }
        }
        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }

    allprojects {
        repositories {
            jcenter()
            flatDir {
                dirs 'libs'
            }
            maven { url 'https://maven.fabric.io/public' }
        }
    }
    android {
        defaultConfig {
            multiDexEnabled true
        }

        dexOptions {
            incremental true
            javaMaxHeapSize "4g"
            preDexLibraries false
        }
    }
    dependencies {

        compile('com.twitter.sdk.android:twitter:1.13.0@aar') {
            transitive = true;
        }

        compile 'com.squareup.okhttp:okhttp:2.2.0'
        compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
        compile 'com.squareup.picasso:picasso:2.4.0'
        compile 'com.android.support:recyclerview-v7:23.1.0'
        compile 'com.google.android.gms:play-services-gcm:7.3.0'
        compile 'com.google.android.gms:play-services:7.3.0'
        compile 'com.android.support:appcompat-v7:23.2.1'
    }
}

But I have removed the classpath dependencies and tried, even then the same problem.

This is the generated build.gradle,

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
*/

// GENERATED FILE! DO NOT EDIT!

apply plugin: 'android'

buildscript {
    repositories {
        mavenCentral()
    }

    // Switch the Android Gradle plugin version requirement depending on the
    // installed version of Gradle. This dependency is documented at
    // http://tools.android.com/tech-docs/new-build-system/version-compatibility
    // and https://issues.apache.org/jira/browse/CB-8143
    if (gradle.gradleVersion >= "2.2") {
        dependencies {
            classpath 'com.android.tools.build:gradle:1.0.0+'
        }
    } else if (gradle.gradleVersion >= "2.1") {
        dependencies {
            classpath 'com.android.tools.build:gradle:0.14.0+'
        }
    } else {
        dependencies {
            classpath 'com.android.tools.build:gradle:0.12.0+'
        }
    }
}

// Allow plugins to declare Maven dependencies via build-extras.gradle.
repositories {
    mavenCentral()
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.2.1'
}

// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.
// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.html
ext {
    apply from: 'CordovaLib/cordova.gradle'
    // The value for android.compileSdkVersion.
    if (!project.hasProperty('cdvCompileSdkVersion')) {
        cdvCompileSdkVersion = null;
    }
    // The value for android.buildToolsVersion.
    if (!project.hasProperty('cdvBuildToolsVersion')) {
        cdvBuildToolsVersion = null;
    }
    // Sets the versionCode to the given value.
    if (!project.hasProperty('cdvVersionCode')) {
        cdvVersionCode = null
    }
    // Sets the minSdkVersion to the given value.
    if (!project.hasProperty('cdvMinSdkVersion')) {
        cdvMinSdkVersion = null
    }
    // Whether to build architecture-specific APKs.
    if (!project.hasProperty('cdvBuildMultipleApks')) {
        cdvBuildMultipleApks = null
    }
    // .properties files to use for release signing.
    if (!project.hasProperty('cdvReleaseSigningPropertiesFile')) {
        cdvReleaseSigningPropertiesFile = null
    }
    // .properties files to use for debug signing.
    if (!project.hasProperty('cdvDebugSigningPropertiesFile')) {
        cdvDebugSigningPropertiesFile = null
    }
    // Set by build.js script.
    if (!project.hasProperty('cdvBuildArch')) {
        cdvBuildArch = null
    }

    // Plugin gradle extensions can append to this to have code run at the end.
    cdvPluginPostBuildExtras = []
}

// PLUGIN GRADLE EXTENSIONS START
// PLUGIN GRADLE EXTENSIONS END

def hasBuildExtras = file('build-extras.gradle').exists()
if (hasBuildExtras) {
    apply from: 'build-extras.gradle'
}

// Set property defaults after extension .gradle files.
if (ext.cdvCompileSdkVersion == null) {
    ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()
}
if (ext.cdvBuildToolsVersion == null) {
    ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()
}
if (ext.cdvDebugSigningPropertiesFile == null && file('debug-signing.properties').exists()) {
    ext.cdvDebugSigningPropertiesFile = 'debug-signing.properties'
}
if (ext.cdvReleaseSigningPropertiesFile == null && file('release-signing.properties').exists()) {
    ext.cdvReleaseSigningPropertiesFile = 'release-signing.properties'
}

// Cast to appropriate types.
ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();
ext.cdvMinSdkVersion = cdvMinSdkVersion == null ? null : Integer.parseInt('' + cdvMinSdkVersion)
ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)

def computeBuildTargetName(debugBuild) {
    def ret = 'assemble'
    if (cdvBuildMultipleApks && cdvBuildArch) {
        def arch = cdvBuildArch == 'arm' ? 'armv7' : cdvBuildArch
        ret += '' + arch.toUpperCase().charAt(0) + arch.substring(1);
    }
    return ret + (debugBuild ? 'Debug' : 'Release')
}

// Make cdvBuild a task that depends on the debug/arch-sepecific task.
task cdvBuildDebug
cdvBuildDebug.dependsOn {
    return computeBuildTargetName(true)
}

task cdvBuildRelease
cdvBuildRelease.dependsOn {
    return computeBuildTargetName(false)
}

task cdvPrintProps << {
    println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)
    println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)
    println('cdvVersionCode=' + cdvVersionCode)
    println('cdvMinSdkVersion=' + cdvMinSdkVersion)
    println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)
    println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)
    println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)
    println('cdvBuildArch=' + cdvBuildArch)
    println('computedVersionCode=' + android.defaultConfig.versionCode)
    android.productFlavors.each { flavor ->
        println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)
    }
}

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }
    }

    defaultConfig {
        versionCode cdvVersionCode ?: Integer.parseInt("" + privateHelpers.extractIntFromManifest("versionCode") + "0")
        if (cdvMinSdkVersion != null) {
            minSdkVersion cdvMinSdkVersion
        }
    }

    compileSdkVersion cdvCompileSdkVersion
    buildToolsVersion cdvBuildToolsVersion

    if (Boolean.valueOf(cdvBuildMultipleApks)) {
        productFlavors {
            armv7 {
                versionCode cdvVersionCode ?: defaultConfig.versionCode + 2
                ndk {
                    abiFilters "armeabi-v7a", ""
                }
            }
            x86 {
                versionCode cdvVersionCode ?: defaultConfig.versionCode + 4
                ndk {
                    abiFilters "x86", ""
                }
            }
            all {
                ndk {
                    abiFilters "all", ""
                }
            }
        }
    } else if (!cdvVersionCode) {
      def minSdkVersion = cdvMinSdkVersion ?: privateHelpers.extractIntFromManifest("minSdkVersion")
      // Vary versionCode by the two most common API levels:
      // 14 is ICS, which is the lowest API level for many apps.
      // 20 is Lollipop, which is the lowest API level for the updatable system webview.
      if (minSdkVersion >= 20) {
        defaultConfig.versionCode += 9
      } else if (minSdkVersion >= 14) {
        defaultConfig.versionCode += 8
      }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_6
        targetCompatibility JavaVersion.VERSION_1_6
    }

    if (cdvReleaseSigningPropertiesFile) {
        signingConfigs {
            release {
                // These must be set or Gradle will complain (even if they are overridden).
                keyAlias = ""
                keyPassword = "__unset" // And these must be set to non-empty in order to have the signing step added to the task graph.
                storeFile = null
                storePassword = "__unset"
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
        addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)
    }
    if (cdvDebugSigningPropertiesFile) {
        addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    // SUB-PROJECT DEPENDENCIES START
    debugCompile project(path: "CordovaLib", configuration: "debug")
    releaseCompile project(path: "CordovaLib", configuration: "release")
    // SUB-PROJECT DEPENDENCIES END
}

def promptForReleaseKeyPassword() {
    if (!cdvReleaseSigningPropertiesFile) {
        return;
    }
    if ('__unset'.equals(android.signingConfigs.release.storePassword)) {
        android.signingConfigs.release.storePassword = privateHelpers.promptForPassword('Enter key store password: ')
    }
    if ('__unset'.equals(android.signingConfigs.release.keyPassword)) {
        android.signingConfigs.release.keyPassword = privateHelpers.promptForPassword('Enter key password: ');
    }
}

gradle.taskGraph.whenReady { taskGraph ->
    taskGraph.getAllTasks().each() { task ->
        if (task.name == 'validateReleaseSigning') {
            promptForReleaseKeyPassword()
        }
    }
}

def addSigningProps(propsFilePath, signingConfig) {
    def propsFile = file(propsFilePath)
    def props = new Properties()
    propsFile.withReader { reader ->
        props.load(reader)
    }

    def storeFile = new File(props.get('key.store') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'storeFile'))
    if (!storeFile.isAbsolute()) {
        storeFile = RelativePath.parse(true, storeFile.toString()).getFile(propsFile.getParentFile())
    }
    if (!storeFile.exists()) {
        throw new FileNotFoundException('Keystore file does not exist: ' + storeFile.getAbsolutePath())
    }
    signingConfig.keyAlias = props.get('key.alias') ?: privateHelpers.ensureValueExists(propsFilePath, props, 'keyAlias')
    signingConfig.keyPassword = props.get('keyPassword', props.get('key.alias.password', signingConfig.keyPassword))
    signingConfig.storeFile = storeFile
    signingConfig.storePassword = props.get('storePassword', props.get('key.store.password', signingConfig.storePassword))
    def storeType = props.get('storeType', props.get('key.store.type', ''))
    if (!storeType) {
        def filename = storeFile.getName().toLowerCase();
        if (filename.endsWith('.p12') || filename.endsWith('.pfx')) {
            storeType = 'pkcs12'
        } else {
            storeType = signingConfig.storeType // "jks"
        }
    }
    signingConfig.storeType = storeType
}

for (def func : cdvPluginPostBuildExtras) {
    func()
}

// This can be defined within build-extras.gradle as:
//     ext.postBuildExtras = { ... code here ... }
if (hasProperty('postBuildExtras')) {
    postBuildExtras()
}
Neela
  • 1,328
  • 4
  • 23
  • 45
  • Are you using direct class path or if else with gradle ? It looks like you have a mismatch between the Gradle plugin itself and its dependencies. – Jay Rathod May 09 '16 at 06:16
  • I have edited the question with my build-extras.gradle.. – Neela May 09 '16 at 06:24
  • @Neela Are you using custom build.gradle too? – Gandhi May 09 '16 at 06:27
  • Yes. I mean, in cordova to use custom build.gradle can be achieved by build-extras.gradle right? Thats what I am doing. And my build-extras.gradle is above. – Neela May 09 '16 at 06:30
  • @Neela The `Classpath` which you removed ? what version it contains ? – Jay Rathod May 09 '16 at 06:32
  • @Neela i suspect build-extras.gradle could be the possbile problem as the same exact build.gradle dependencies you posted works for me. Could you try adding "dependencies { classpath 'com.android.tools.build:gradle:2.0.0' }" in your build-extras.gradle and check once – Gandhi May 09 '16 at 06:32
  • @Gandhi I have tried it, but still the same problem. Problem seems to be, it doesn't check the build-extras at all. Whatever I change in the build-extras, it remains the same. – Neela May 09 '16 at 06:40
  • @jaydroider this is it. classpath 'com.android.tools.build:gradle:2.0.0' – Neela May 09 '16 at 06:41
  • @Neela I would suggest you to use `dependencies { classpath 'com.android.tools.build:gradle:2.0.0-beta5' } ` this version. Give a try and check. – Jay Rathod May 09 '16 at 06:43
  • @jaydroider Still the same. :( Is it because of the cordova version? I use 5.4.0 instead of 6.1.1. I purposely need to use this version. – Neela May 09 '16 at 06:48
  • @Neela If build-extras is not considered, are you able to build by removing this file? Just for verification – Gandhi May 09 '16 at 06:55
  • @Neela It could be possible conflicts of cordova version. Bcz which version i have suggested above is the newest version for this. – Jay Rathod May 09 '16 at 06:58
  • @Neela As you mentioned the build-extras changes are not considered, i request you to have a look at this link - http://stackoverflow.com/questions/29386152/override-java-version-when-building-a-cordova-project-with-gradle which may help – Gandhi May 09 '16 at 07:01
  • @Gandhi I tried by removing it, even then it is not working. – Neela May 09 '16 at 08:04
  • @Neela Any specific reason to stick to cordova version 5.4.0? I believe updating cordova and removing android platform and re-adding it should resolve this issue – Gandhi May 09 '16 at 09:44
  • Yes I know, but client machine is having that version and its necessary for me to use the same.. – Neela May 09 '16 at 10:03
  • @Neela Could you try uninstalling and reinstalling cordova 5.4.0? – Gandhi May 09 '16 at 14:06
  • It works only with 6.1.1, Not with 5.4.0. The build.gradle file generated by these two versions are different and the one by 5.4.0 is not appropriate to work with. – Neela May 10 '16 at 06:57
  • @Neela Can you share the build.gradle generated? What is the conclusion then? – Gandhi May 10 '16 at 14:32
  • @Gandhi, I have editted the question with generated build.gradle. – Neela May 11 '16 at 09:16
  • @Gandhi I think I need to go with hooks after_build. Since I am beginner in cordova, I dont know how to write hooks for this. – Neela May 11 '16 at 09:17
  • @Neela after_build hooks will execute after successful build rite? You were telling that you were unable to build. How does that help? – Gandhi May 11 '16 at 09:59
  • @Gandhi I dont have experience on hooks. So what should I try now? – Neela May 12 '16 at 06:42
  • @Neela Just have a lool at this link - http://doc.siberiancms.com/knowledge-base/how-to-publish-android-apps/ and see if the suggested settings work. In worst, you may have to directly edit the build.gradle and build the android platform. Once it works, you may write a pre build action to overwrite the build.gradle from your project to build,gradle in android platform (although not recommended) – Gandhi May 12 '16 at 06:53
  • @Gandhi, since I am new to hooks, is it possible for you to give me an example hooks? Say for example to edit the classpath. – Neela May 13 '16 at 07:21
  • @Neela As i mentioned in earlier comment, you may write a pre build action to overwrite the build.gradle from your project to build,gradle in android platform. This can be acheived through a simple windows batch file too. Once the batch file is ready, you can hook the same by adding "" in config.xml so that it automatically overwrites the file before build. More info on hooks can be found at http://cordova.apache.org/docs/en/6.x/guide/appdev/hooks/index.html#page-toc-source – Gandhi May 13 '16 at 07:44
  • @Neela Not sure whether you tried out the approach. But i recently figured out one more approach to refer to local gradle installation and build android platform. Suggest you to check out this link - http://stackoverflow.com/questions/37254222/cordova-build-error-exit-code-1/37257413 – Gandhi May 20 '16 at 05:44
  • @Neela Sorry for getting back on this so late. Did you cracked it? – Gandhi Jun 06 '16 at 15:52
  • @Gandhi, yes through hooks.. – Neela Jun 07 '16 at 09:02
  • @Gandhi I have customized buil.gradle as per my need using hooks, "after_prepare" – Neela Jun 07 '16 at 09:04
  • @Neela So managed it with batch file on after_prepare hook? Was my suggestions helpful? – Gandhi Jun 07 '16 at 10:01
  • @Gandhi, ofcourse yes.. – Neela Jun 07 '16 at 10:47
  • @Neela I just wanted to post the answer so that you can accept the same and it will be helpful for others too. Also please keep us informed so that it motivates us too :) – Gandhi Jun 07 '16 at 10:59
  • @Neela We earlier discussed about hooks rite. You can take a look at the working sample here - https://github.com/gandhirajan/Cordova_Hooks – Gandhi Jul 22 '16 at 11:37

2 Answers2

1

You may write a pre build action to overwrite the build.gradle from your project to build.gradle in android platform. This can be achieved through a simple windows batch file too.

Once the batch file is ready, you can hook the same by adding:

"<hook type="before_build" src="scripts/batch_file_name.bat" />" in config.xml so that it automatically overwrites the file before build.

More info on hooks can be found at official cordova hooks documentation.

Gandhi
  • 11,875
  • 4
  • 39
  • 63
0

Try with this in your project level build.gradle.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.google.gms:google-services:2.0.0-alpha5'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Let me know, if anything going wrong.

Dhruv
  • 1,801
  • 1
  • 15
  • 27