Autocompletion not working in Android Studio Arctic Fox inside buildSrc - android-studio

I am writing a custom plugin inside buildSrc using Android Studio Arctic Fox installed by brew. After some tests, there is a problem with the autocompletion of imports. It works inside app/build.gradle.kts that I can do import com.android.build.api.dsl.*, but inside buildSrc this raised Unresolved reference on android namespace.
The root build.gradle.kts:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
extra["kotlin_version"] = "1.4.32"
classpath("com.android.tools.build:gradle:7.0.2")
classpath(kotlin("gradle-plugin", version = "1.4.32"))
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
tasks.register("clean", Delete::class) {
delete(rootProject.buildDir)
}
build.gradle.kts under buildSrc:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.4.31"
`kotlin-dsl`
}
repositories {
google()
mavenCentral()
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = "11"
apiVersion = "1.4"
}
}
dependencies {
implementation("com.android.tools.build:gradle:7.0.2")
implementation("com.android.tools.build:gradle-api:7.0.2")
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.32")
implementation(kotlin("stdlib"))
gradleApi()
}
build.gradle.kts under app:
import com.example.pythonLibs
plugins {
id("com.android.application")
kotlin("android")
id("com.example.plugin")
}
android {
compileSdk = 30
ndkVersion = "23.0.7599858"
sourceSets {
getByName("main") {
pythonLibs {
srcDir("src/main/pythonLibs")
}
}
}
defaultConfig {
applicationId = "com.example.embedpythontest"
minSdk = 23
targetSdk = 30
versionCode = 1
versionName = "1.0.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
// consumerProguardFiles = [file("consumer-rules.pro")]
externalNativeBuild {
cmake {
//arguments("-DANDROID_STL=c++_shared")
//cppFlags("")
}
}
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
externalNativeBuild {
cmake {
path = file("src/main/cpp/CMakeLists.txt")
version = "3.21.3"
}
}
compileOptions {
sourceCompatibility(JavaVersion.VERSION_11)
targetCompatibility(JavaVersion.VERSION_11)
}
kotlinOptions {
jvmTarget = "11"
apiVersion = "1.4"
}
}
dependencies {
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
implementation("androidx.appcompat:appcompat:1.3.1")
implementation("com.google.android.material:material:1.4.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.1")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.3")
androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0")
}
in all files under buildSrc/src/main/kotlin/**, when doing import com.android.build.api.dsl.*, a problem shown but build project is ok. But if I do import inside buildSrc/build.gradle.kts, it won't be compiled. But the same thing could be done inside app/build.gradle.kts.
Why Android Studio cannot find the class?

This problem is caused by not being familiar with the dependencies in Gradle. After changing the dependncy block to:
dependencies {
implementation("com.android.tools.build:gradle-api:7.0.2")
implementation(kotlin("stdlib"))
gradleApi()
}
which copied from here that would solve the problem.

Related

Android Studio: Error "Failed to resolve: design"?

Hi I receive this error message on gradle project sync.
"Failed to resolve: design"
I can't find what's this.
Is there any friend that can help me with this? Or do you have another icon pack Android Studio project?
It's from CandyBar-Sample-Master android icon pack project.
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.CompileSdk
android.applicationVariants.all { variant ->
variant.outputs.all { output ->
def appName = parent.name
def fileName = appName.replace(" ", "_")
outputFileName = "$fileName-v${variant.versionName}.apk"
}
}
defaultConfig {
applicationId "com.grafiman.icons.selero"
minSdkVersion rootProject.ext.MinSdk
targetSdkVersion rootProject.ext.TargetSdk
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
buildToolsVersion '27.0.3'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.github.danimahardhika.candybar-library:core:3.5.0-b4'
}
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
jcenter()
google()
maven { url "https://jitpack.io" }
maven { url 'https://maven.google.com' }
}
//NOTE: This is important
rootProject.ext {
BuildTools = "27.0.3"
MinSdk = 15
TargetSdk = 26
CompileSdk = 26
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

Android Studio Wikitude Native SDK Issue

So im trying to first build a basic app using android studio and Wikitudes Native SDK to make an AR app. After following the setup instructions ive ran into an error I cant seem to solve but have an idea of why/where its happening. Does anyone know what could be causing these errors?
This image here shows the errors I am getting and what looks to be an issue with a few of the imports
Here is also a copy of my build.gradle file (Module: app), and my build.gradle file (Module: NativeSDKExamples), respectively:
apply plugin: 'com.android.application'
android {
compileSdkVersion commonCompileSdkVersion
buildToolsVersion commonBuildToolsVersion
defaultConfig {
applicationId "com.uhg.ent.mobile.lifesciences.amplify"
minSdkVersion commonMinSdkVersion
targetSdkVersion commonTargetSdkVersion
versionCode 1
versionName "7.2.1"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable true
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
def fileName = "app-" + variant.buildType.name + ".apk"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
flavorDimensions "arch"
productFlavors {
arm7 {
dimension "arch"
}
arm8 {
dimension "arch"
}
x86 {
dimension "arch"
}
allarchs {
dimension "arch"
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile (name: 'wikitude-native-sdk', ext:'aar')
arm7Compile project(path: ':plugins', configuration: 'arm7Release')
arm8Compile project(path: ':plugins', configuration: 'arm8Release')
x86Compile project(path: ':plugins', configuration: 'x86Release')
allarchsCompile project(path: ':plugins', configuration: 'allarchsRelease')
compile "com.android.support:appcompat-v7:$commonSupportLibVersion"
compile "com.android.support:design:$commonSupportLibVersion"
compile "com.android.support:support-v4:$commonSupportLibVersion"
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android:flexbox:0.2.5'
}
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
AND
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
subprojects {
ext.commonCompileSdkVersion = 26
ext.commonBuildToolsVersion = "26.0.0"
ext.commonMinSdkVersion = 19
ext.commonTargetSdkVersion = 26
ext.commonSupportLibVersion = "26.0.0"
}
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
}

Convert an existing groovy build.gradle file into a kotlin based build.gradle.kts

my project has two different build.gradle files written with groovy Syntax.
I´d like to change this groovy written gradle file into a gradle file written with Kotlin Syntax (build.gradle.kts).
I´ll show you the root project build.gradle file.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
//ext.kotlin_version = '1.2-M2'
ext.kotlin_version = '1.1.51'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0-alpha01'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
I tried several "ways" i found in the internet, but nothing worked. Renaming the file, which is obviously not the Solution, didn´t help. I´ve created a new build.gradle.kts file in my root project but the file isn´t shown in my project.
Also gradle didn´t recognize the new file.
So my question is: How can i transform my groovy build.gradle file into a kotlin build.gradle.kts and add this new file into my existing project?
Thanks for your help.
Of course renaming won't help. You'll need to re-write it using Kotlin DSL. It is similar to Groovy, but with some differences. Read their docs, look at the examples.
In your case, the issues are:
ext.kotlin_version is not valid Kotlin syntax, use square brackets
All Kotlin strings use double quotes
Braces are required around parameters for most function calls (there are exceptions, like infix functions)
Slighlty different task management API. There are different styles available. You can declare all the tasks in tasks block as strings, or use a single typed function, as in the example below.
Take a look at the converted top-level build.gradle.kts:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext["kotlin_version"] = "1.1.51"
repositories {
google()
jcenter()
}
dependencies {
classpath ("com.android.tools.build:gradle:3.1.0-alpha01")
classpath ("org.jetbrains.kotlin:kotlin-gradle-plugin:${ext["kotlin_version"]}")
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
task<Delete>("clean") {
delete(rootProject.buildDir)
}
buildscript {
extra.apply {
var kotlin_version = "1.7.10"
var navigationVersion = "2.5.0"
var hilt_version = "2.42"
}
// .kotlin_version("1.7.10")
// ext.navigationVersion("2.5.0")
// ext.hilt_version("2.42")
repositories {
gradlePluginPortal()
google()
mavenCentral()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:7.2.1")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10")
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0")
classpath("com.google.firebase:firebase-crashlytics-gradle:2.9.1")
classpath("com.google.gms:google-services:4.3.13")
classpath("com.google.firebase:perf-plugin:1.4.1")
classpath("com.google.dagger:hilt-android-gradle-plugin:2.42")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// classpath("com.google.dagger:hilt-android-gradle-plugin:$extra.hilt_version")
}
}
allprojects {
repositories {
gradlePluginPortal()
mavenCentral()
google()
jcenter()
maven { url = uri("https://jitpack.io") }
maven { url = uri("https://cdn.veriff.me/android/") }
flatDir {
dirs("libs")
}
}
}
tasks.register("clean"){
delete(setOf(rootProject.buildDir))
}
import extensions.*
import java.time.LocalDate
import java.time.format.DateTimeFormatter.*
plugins {
id(Plugins.ANDROID_APPLICATION)
id(Plugins.ANDROID)
id(Plugins.PARCELIZE)
id(Plugins.KAPT)
id(Plugins.NAVIGATION_SAFE_ARGS)
id(Plugins.GOOGLE_SERVICES)
id(Plugins.CRASH_ANALYTICS)
id(Plugins.PERFORMANCE_ANALYTICS)
id(Plugins.DAGGER_HILT)
}
var applicationName = "abc`enter code here`"
android {
compileSdk = AndroidConfig.COMPILE_SDK
bundle {
language {
enableSplit = false
}
}
defaultConfig {
configurations.all {
resolutionStrategy { force(AndroidConfig.FORCE_STRATEGY) }
}
applicationId = AndroidConfig.APPLICATION_ID
minSdkVersion(AndroidConfig.MIN_SDK)
targetSdkVersion(AndroidConfig.TARGET_SDK)
versionCode = AndroidConfig.VERSION_CODE
versionName = AndroidConfig.VERSION_NAME
testInstrumentationRunner = AndroidConfig.TEST_INSTRUMENTATION_RUNNER
//javaCompileOptions.annotationProcessorOptions.arguments['dagger.hilt.disableModulesHaveInstallInCheck'] = 'true'
}
applicationVariants.all {
outputs.all {
var formattedDate = LocalDate.now()//LocalDate.now().format(ofPattern("yyyy-MM-dd"))
var outputFileName =
"${applicationName}_${buildType.name}_${formattedDate}_v${defaultConfig.versionName}.apk"
}
}
buildTypes {
getByName("debug") {
// minifyEnabled = "false"
isMinifyEnabled = false
isTestCoverageEnabled = true
isShrinkResources = false
isDebuggable = true
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
testProguardFiles(getDefaultProguardFile("proguard-android.txt"),
"proguardTest-rules.pro")
// FirebasePerformance {
// // Set this flag to 'false' to disable #AddTrace annotation processing and
// // automatic HTTP/S network request monitoring
// // for a specific build variant at compile time.
// isInstrumentationEnabled = true
// }
}
getByName("release") {
isMinifyEnabled = false
isShrinkResources = false
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
testProguardFiles(getDefaultProguardFile("proguard-android.txt"),
"proguardTest-rules.pro")
}
}
buildFeatures {
viewBinding = true
dataBinding = true
}
// compileOptions {
// sourceCompatibility = JavaVersion.VERSION_11
// targetCompatibility = JavaVersion.VERSION_11
// }
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_11.toString()
//freeCompilerArgs= ["-Xjvm-default=compatibility"]
freeCompilerArgs = listOf("-Xjvm-default=compatibility")
// freecompilerargs = List( -Xjvm-default=compatibility)
}
flavorDimensions("mode")
productFlavors {
maybeCreate("Staging")
maybeCreate("PreProduction")
maybeCreate("Production")
getByName("Staging") {
applicationIdSuffix = ".staging"
//versionNameSuffix = ".staging"
}
getByName("Production") {
dimension = "mode"
resValue("string", "app_name", "abc")
}
}
packagingOptions {
resources.excludes += "META-INF/DEPENDENCIES"
resources.excludes += "META-INF/NOTICE"
resources.excludes += "META-INF/LICENSE"
resources.excludes += "META-INF/LICENSE.txt"
resources.excludes += "META-INF/NOTICE.txt"
// excludes += ['META-INF/DEPENDENCIES', 'META-INF/NOTICE', 'META-INF/LICENSE', 'META-INF/LICENSE.txt', 'META-INF/NOTICE.txt']
}
dynamicFeatures += setOf(":BuyCryptoModule",":"points")
}
dependencies {
//includeing file libs
val daggerVersion = "2.42"
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
implementation(files("geetest_captcha_android_v1.7.1.1_20220308"))
appModuleDeps()
kaptAndroidTest("com.google.dagger:hilt-compiler:2.42")
// For local unit tests
testImplementation("com.google.dagger:hilt-android-testing:2.42")
kaptTest("com.google.dagger:hilt-compiler:2.42")
implementation(files("libs/opencsv-5.2.jar"))
kaptAndroidTest("com.google.dagger:dagger-compiler:$daggerVersion")
kaptTest("com.google.dagger:dagger-compiler:$daggerVersion")
releaseImplementation("com.github.ChuckerTeam.Chucker:library-no-op:3.5.2")
}
kapt {
correctErrorTypes = true
arguments {
// Make Hilt share the same definition of Components in tests instead of
// creating a new set of Components per test class.
arg("dagger.hilt.shareTestComponents", "true")
}
}

How to generate on the fly Java source code to build with Gradle in Android Studio?

As part of an Android app that uses the NDK, I need to export some constants from the C/C++ world into Java. For obvious reasons, I'd rather have this automated. I'm using Android Studio with the NDK support.
How can I generate some .java file on the fly from a shell script that would be ran by Gradle whenever the app builds? Ideally this .java file would go in an build intermediaries directory somewhere and wouldn't have to be in the app source directory.
As an example, the shell script would generate this Java source:
public enum Type {
FOO,
BAR
}
from this C++ source:
enum class Type {
FOO,
BAR
}
For reference here's a simplified version of the Gradle file I'm starting from in Android Studio:
apply plugin: 'com.android.model.application'
model {
compileOptions.with {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.2"
defaultConfig.with {
applicationId = "..."
minSdkVersion.apiLevel = 18
targetSdkVersion.apiLevel = 23
}
defaultConfig.multiDexEnabled = true
}
android.ndk {
platformVersion = "18"
moduleName = "jni"
...
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles.add(file('proguard-rules.txt'))
ndk.with {
CFlags.add("-Werror")
cppFlags.add("-Werror")
}
}
}
android.productFlavors {
create("arm7") {
ndk.abiFilters.add("armeabi-v7a")
}
}
}
repositories {
...
}
dependencies {
...
}
apply plugin: 'com.google.gms.google-services'
You could just write the generated file to the $buildDir/generatedJava then add that directory as a source folder. Then make the task javaCompile depend on your task that generates the source. Something like this could be used inside a build.gradle
def outputJavaFile = new File("$buildDir.absolutePath/generatedJava", 'MyEnum.java')
task generateSources(type: Exec) {
def source = $/
package com.example;
public enum Something {
One,
Two
}
/$
if (!outputJavaFile.parentFile.exists()) {
outputJavaFile.parentFile.mkdirs()
}
outputJavaFile.withWriter {
it << source
}
}
compileJava.dependsOn outputJavaFile
sourceSets {
main {
java {
srcDirs 'src/main/java', outputJavaFile.absolutePath
}
}
}
// if the goal is to generate the source from a script then just call the script
// inside the Exec closure
task shellScriptToGenerateSources(type: Exec) {
commandLine 'myShellScript.sh'
}
// then make compileJava depend on the task that runs the script
compileJava.dependsOn shellScriptToGenerateSources
Edit: To apply the same logic to your updated build.gradle file might look something like this
apply plugin: 'com.android.model.application'
// define an output folder for our generated .java files
def GENERATED_JAVA_OUTPUT = "$buildDir/generatedJava"
// if the goal is to generate the source from a script then just call the script
// inside the Exec closure
task shellScriptToGenerateSources(type: Exec) {
commandLine 'myShellScript.sh'
}
// then make compileJava depend on the task that runs the script
compileJava.dependsOn shellScriptToGenerateSources
model {
compileOptions.with {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.2"
defaultConfig.with {
applicationId = "..."
minSdkVersion.apiLevel = 18
targetSdkVersion.apiLevel = 23
}
defaultConfig.multiDexEnabled = true
}
android.ndk {
platformVersion = "18"
moduleName = "jni"
...
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles.add(file('proguard-rules.txt'))
ndk.with {
CFlags.add("-Werror")
cppFlags.add("-Werror")
}
}
}
android.productFlavors {
create("arm7") {
ndk.abiFilters.add("armeabi-v7a")
}
}
// let android know that our java sources shoudl also consider the generated java for the compiler
android.sourceSet {
main {
java {
srcDir(GENERATED_JAVA_OUTPUT)
}
}
}
}
repositories {
...
}
dependencies {
...
}
apply plugin: 'com.google.gms.google-services'

How to use new gradle experimental in Android Studio

I made a very hello world with Android Studio NDK. As instructed from http://tools.android.com/tech-docs/new-build-system/gradle-experimental, I copied exactly the same (left only some newer build tool version), but the error always appears:
Error:(49, 1) A problem occurred evaluating project ':app'.
Could not find method testCompile() for arguments [junit:junit:4.12] on project ':app'.
Could you tell me what's problem with my HelloWorld?
Here's my app build.gradle
apply plugin: "com.android.model.application"
model {
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig.with {
applicationId = "com.android.services.testjni"
minSdkVersion.apiLevel = 15
targetSdkVersion.apiLevel = 23
versionCode = 1
versionName = "1.0"
buildConfigFields.with {
create() {
type = "int"
name = "VALUE"
value = "1"
}
}
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles.add(file("proguard-rules.pro"))
}
}
android.productFlavors {
create("flavor1") {
applicationId = "com.app"
}
}
// Configures source set directory.
android.sources {
main {
java {
source {
srcDir "src"
}
}
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
}
and build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle-experimental:0.2.1"
// 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
}
and gradle-wrapper.properties
#Fri Nov 27 17:00:16 ICT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-all.zip
AFAIK, android plugin doesn't have a testCompile configuration, which is one from gradle's java plugin, but has an androidTestCompile. So, you have to rename it in your dependencies, as:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
}

Resources