how to convert build.gradle.kts to old build.gradle - android

I want to convert this file in old build.gradle file, I am doing but there are alot of errors.
have searched too many google links but nothing happened.
I want to convert this file in old build.gradle file, I am doing but there are alot of errors.
have searched too many google links but nothing happened.
import com.android.build.gradle.api.ApplicationVariant
plugins {
id("com.android.application")
kotlin("android")
kotlin("android.extensions")
}
android {
compileSdkVersion(29)
defaultConfig {
minSdkVersion(14)
targetSdkVersion(29)
versionCode = 1
versionName = "0.1.1"
externalNativeBuild {
cmake {
}
}
}
externalNativeBuild {
cmake {
setPath(File("${projectDir}/src/main/cpp/CMakeLists.txt"))
}
}
sourceSets {
getByName("main") {
assets.srcDirs("src/main/assets", "build/ovpnassets")
}
getByName("debug") {
}
getByName("release") {
}
}
lintOptions {
enable("BackButton", "EasterEgg")
warning("ImpliedQuantity", "MissingQuantity")
disable("MissingTranslation", "UnsafeNativeCodeLocation")
}
buildTypes {
getByName("release") {
if (project.hasProperty("icsopenvpnDebugSign")) {
logger.warn("property icsopenvpnDebugSign set, using debug signing for release")
signingConfig = android.signingConfigs.getByName("debug")
} else {
signingConfig = signingConfigs.getByName("release")
}
}
}
flavorDimensions("implementation")
productFlavors {
create("ui") {
setDimension("implementation")
buildConfigField("boolean", "openvpn3", "true")
}
}
splits {
abi {
isEnable = true
reset()
include("x86", "x86_64", "armeabi-v7a", "arm64-v8a")
isUniversalApk = true
}
}
}
var swigcmd = "swig"
if (File("/usr/local/bin/swig").exists())
swigcmd = "/usr/local/bin/swig"
fun registerGenTask(variantName: String, variantDirName: String): File {
val baseDir = File(buildDir, "generated/source/ovpn3swig/${variantDirName}")
val genDir = File(baseDir, "net/openvpn/ovpn3")
tasks.register<Exec>("generateOpenVPN3Swig${variantName}")
{
doFirst {
mkdir(genDir)
}
commandLine(listOf(swigcmd, "-outdir", genDir, "-outcurrentdir", "-c++", "-java", "-package", "net.openvpn.ovpn3",
"-Isrc/main/cpp/openvpn3/client", "-Isrc/main/cpp/openvpn3/",
"-o", "${genDir}/ovpncli_wrap.cxx", "-oh", "${genDir}/ovpncli_wrap.h",
"src/main/cpp/openvpn3/javacli/ovpncli.i"))
}
return baseDir
}
android.applicationVariants.all(object : Action<ApplicationVariant> {
override fun execute(variant: ApplicationVariant) {
val sourceDir = registerGenTask(variant.name, variant.baseName.replace("-", "/"))
val task = tasks.named("generateOpenVPN3Swig${variant.name}").get()
variant.registerJavaGeneratingTask(task, sourceDir)
}
})
dependencies {
val preferenceVersion = "1.1.0"
implementation("androidx.annotation:annotation:1.1.0")
implementation("androidx.core:core:1.1.0")
dependencies.add("uiImplementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.50")
dependencies.add("uiImplementation", "androidx.core:core:$coreVersion")
dependencies.add("uiImplementation", "androidx.core:core-ktx:$coreVersion")
dependencies.add("uiImplementation", "androidx.fragment:fragment-ktx:1.1.0")
dependencies.add("uiImplementation", "androidx.preference:preference:$preferenceVersion")
dependencies.add("uiImplementation", "androidx.preference:preference-ktx:$preferenceVersion")
testImplementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.61")
}

Related

All .kts files become unresolved after upgrading to gradle 7.42, how can I solve this problem?

When I upgrade gradle version from 7.33 to 7.41 or higher. Every line in every gradle.kts become unresolved. I tried to replace all lines(except namespace) in corresponding files of a new project created from Android Studio template and there is no problem. I can't figure out what's wrong in my existing project.
project build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("com.android.application")
kotlin("android")
kotlin("kapt")
//id("dagger.hilt.android.plugin")
id("com.google.devtools.ksp") version "1.6.21-1.0.5"
}
val composeVersion: String = rootProject.extra["composeVersion"] as String
val coroutinesVersion: String = rootProject.extra["coroutinesVersion"] as String
android {
compileSdk = 32
defaultConfig {
applicationId = "com.app.myapp"
minSdk = 24
targetSdk = 32
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
)
}
getByName("debug") {
applicationIdSuffix = ".debug"
versionNameSuffix = "-debug"
}
}
compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility(JavaVersion.VERSION_11)
targetCompatibility(JavaVersion.VERSION_11)
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions.freeCompilerArgs += "-opt-in=org.mylibrary.OptInAnnotation"
kotlinOptions.jvmTarget = JavaVersion.VERSION_11.toString()
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = composeVersion
}
packagingOptions {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
namespace = "com.app.myapp"
applicationVariants.all {
kotlin.sourceSets {
getByName(name) {
kotlin.srcDir("build/generated/ksp/$name/kotlin")
}
}
}
}
dependencies {
implementation("androidx.core:core-ktx:1.7.0")
// Jetpack Compose
implementation("androidx.compose.ui:ui:$composeVersion")
implementation("androidx.compose.material:material:$composeVersion")
implementation("androidx.compose.ui:ui-tooling-preview:$composeVersion")
debugImplementation("androidx.compose.ui:ui-tooling:$composeVersion")
implementation("androidx.compose.foundation:foundation:$composeVersion")
implementation("androidx.compose.material:material-icons-core:$composeVersion")
implementation("androidx.activity:activity-compose:1.4.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1")
implementation("com.google.accompanist:accompanist-systemuicontroller:0.24.9-beta")
implementation("com.google.accompanist:accompanist-permissions:0.24.9-beta")
// Material design 3
implementation("androidx.compose.material3:material3:1.0.0-alpha12")
implementation("androidx.compose.material3:material3-window-size-class:1.0.0-alpha12")
// Navigation
implementation("androidx.navigation:navigation-compose:2.4.2")
implementation("io.github.raamcosta.compose-destinations:animations-core:1.5.7-beta")
ksp("io.github.raamcosta.compose-destinations:ksp:1.5.7-beta")
// Hilt
/*implementation("com.google.dagger:hilt-android:2.42")
kapt("com.google.dagger:hilt-compiler:2.42")*/
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion")
// Nordic ble library
implementation("no.nordicsemi.android.support.v18:scanner:1.6.0")
implementation("no.nordicsemi.android:ble-ktx:2.4.1")
implementation("no.nordicsemi.android:ble-common:2.4.1")
// Java 8+ API desugaring
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:1.1.5")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.4.1")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.3")
androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0")
androidTestImplementation("androidx.compose.ui:ui-test-junit4:$composeVersion")
}
kapt {
correctErrorTypes = true
}
app build.gradle.kts
buildscript {
val composeVersion by extra("1.2.0-beta02")
val coroutinesVersion by extra("1.6.1")
dependencies {
classpath("com.google.dagger:hilt-android-gradle-plugin:2.42")
}
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id ("com.android.application") version "7.2.0" apply false
id ("com.android.library") version "7.2.0" apply false
id ("org.jetbrains.kotlin.android") version "1.6.21" apply false
}
tasks.register("clean",Delete::class){
delete(rootProject.buildDir)
}
settings.gradle.kts
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "My App"
include(":app")

SourceSet with name 'main' not found

I'd like to Maven publish in my Android app, and I'm using kotlin-dsl for gradle files. This is how I'm trying to publish my code:
subprojects {
plugins.apply("maven-publish")
afterEvaluate {
// Common settings
if (isAndroidLibrary || isAndroidApplication) {
extensions.getByType<com.android.build.gradle.BaseExtension>().apply {
compileSdkVersion(CommonVersions.targetsdk)
buildToolsVersion = CommonVersions.buildTools
defaultConfig {
minSdkVersion(CommonVersions.minsdk)
targetSdkVersion(CommonVersions.targetsdk)
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
buildFeatures.viewBinding = true
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
jvmTarget = "1.8"
}
}
}
}
// Set up publishing configuration
val sourceSets: SourceSetContainer by project
print("project name: $name, ")
print("project size: ${sourceSets.size}, ")
print("project size: ${project.the<SourceSetContainer>().size}, ")
print("project size: ${the<SourceSetContainer>().size}, ")
if (!notPublishingModules.contains(name) && sourceSets.size != 0) {
configure<PublishingExtension> {
publications {
create<MavenPublication>("maven") {
groupId = "xx.yyy.zz"
artifactId = "test"
version = "0.0.0"
from(components.findByName("release"))
val sourcesJar by tasks.creating(Jar::class) {
val sourceSets: SourceSetContainer by project
from(sourceSets["main"].allJava)
classifier = "sources"
}
artifact(sourcesJar)
}
}
}
}
}
}
I always get this error: SourceSet with name 'main' not found.
As you can see I was trying to print the sourceset out, to see if it has any information or not. The size of the sourceset is always zero.
What am I doing wrong?
I use groovy with spring applications , I think you missing this in your code
sourceSets {
main {
java { srcDirs = ["src/java"] }
resources { srcDir "src/resources" }
}
}
where you define where is srcDirs are .

Kotlin Multiplatform build failure due to android target

I am creating a Kotlin Multiplatform library with Android support.
When I try to build with gradle I get an error (./gradlew build --warning-mode all).
Either this:
Could not determine the dependencies of task ':lib:compileDebugAidl'.
> Failed to find target with hash string '29' in: /home/user/Android/Sdk
Or that:
Could not determine the dependencies of task ':lib:verifyReleaseResources'.
> Failed to find target with hash string '29' in: /home/user/Android/Sdk
The first right after indexing and the second when I do ./gradlew clean
However, there is this dependency in any case since I have already created Android apps based on that.
I have also tried Target 28 and an RC version of 30 (since 30 has not yet been officially released, but I have still created apps)
My structure of the gradle files is like this:
root
|-build.gradle.kts
|-settings.gradle.kts
|-gradlew
|-gradlew.bat
|-gradle
|-wrapper
|-gradle-wrapper.jar
|-gradle-wrapper.properties
|-lib
|-build.gradle.kts
settings.gradle.kts:
rootProject.name = "Library"
include(":lib")
root build.gradle.kts:
buildscript {
repositories {
addRepos()
maven(uri("https://dl.bintray.com/kotlin/kotlin-eap")) {
metadataSources {
gradleMetadata()
mavenPom()
}
}
}
dependencies {
classpath("com.android.tools.build:gradle:4.1.0-beta04")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72")
}
}
allprojects {
repositories {
addRepos()
maven(uri("https://dl.bintray.com/kotlin/kotlin-eap")) {
metadataSources {
gradleMetadata()
mavenPom()
}
}
}
}
lib build.gradle.kts:
plugins {
id("com.android.library")
kotlin("multiplatform")
id("maven-publish")
}
group = "de.datlag"
version = "1.0"
android {
compileSdkVersion = 29.toString()
buildToolsVersion = "29.0.3"
defaultConfig {
targetSdkVersion(29)
versionCode = 1
versionName = "1.0"
}
buildTypes {
val debug by getting {
isMinifyEnabled = false
isDebuggable = true
isShrinkResources = false
}
val release by getting {
isMinifyEnabled = false
isDebuggable = false
isShrinkResources = false
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
repositories {
addRepos()
}
kotlin {
jvm {
compilations.all {
kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8.toString()
}
}
js {
browser()
nodejs()
}
android {
publishAllLibraryVariants()
}
val hostOs = System.getProperty("os.name")
val isMingwX64 = hostOs.startsWith("Windows")
val nativeTarget = when {
hostOs == "Mac OS X" -> macosX64("native")
hostOs == "Linux" -> linuxX64("native")
isMingwX64 -> mingwX64("native")
else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
}
sourceSets {
val commonMain by getting {
dependencies {
implementation(kotlin("stdlib-common"))
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
val jvmMain by getting {
dependencies {
implementation(kotlin("stdlib-jdk8"))
}
}
val jvmTest by getting {
dependencies {
implementation(kotlin("test"))
implementation(kotlin("test-junit"))
}
}
val androidMain by getting {
dependsOn(jvmMain)
}
val androidTest by getting {
dependsOn(jvmTest)
}
val jsMain by getting {
dependencies {
implementation(kotlin("stdlib-js"))
}
}
val jsTest by getting {
dependencies {
implementation(kotlin("test-js"))
}
}
val nativeMain by getting { }
val nativeTest by getting { }
}
}
addRepos method:
fun RepositoryHandler.addRepos() {
mavenLocal {
metadataSources {
gradleMetadata()
mavenPom()
}
}
mavenCentral {
metadataSources {
gradleMetadata()
mavenPom()
}
}
jcenter {
metadataSources {
gradleMetadata()
mavenPom()
}
}
google {
metadataSources {
gradleMetadata()
mavenPom()
}
}
gradlePluginPortal()
}
In lib.build.gradle.kts you should use the compileSdkVersion(29) syntax rather than setting a string. You can see in the source for these extensions that the behavior is different if you call the string version.
/** #see #getCompileSdkVersion() */
public void compileSdkVersion(String version) {
checkWritability();
this.target = version;
}
/** #see #getCompileSdkVersion() */
public void compileSdkVersion(int apiLevel) {
compileSdkVersion("android-" + apiLevel);
}
The when passing an int it will append "android-" for you. So you could do compileSdkVersion = "android-29" if you wanted, but just passing the int is easier

Android Studio 3.4 Failed to resolve all Dependencies

I'm using new beta version of Android Studio 3.4 and kotlin dsl as bulding gradle scripts. I have a lot of modules in the project and that's why I write KotlinBuildScript extension for building projects, but I have error message for all external dependencies like "ERROR: Failed to resolve: com.google.dagger:dagger:2.18", "ERROR: Failed to resolve: androidx.recyclerview:recyclerview:1.0.0". How can I fix it?
Here is my root build.gradle.kts:
buildscript {
repositories {
mavenCentral()
jcenter()
google()
maven(url = uri("https://dl.bintray.com/kotlin/kotlin-eap"))
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.10")
}
}
allprojects {
repositories {
mavenCentral()
jcenter()
google()
maven(url = uri("https://dl.bintray.com/kotlin/kotlin-eap"))
}
}
And my KotlinBuildScript:
object Version {
val kotlin = "1.3.10"
val androidx = "1.0.0"
val constraintlayout = "1.1.3"
val lifecycle = "2.0.0"
val paging = "2.1.0-alpha01"
}
fun KotlinBuildScript.setupApplication(applicationId:String, versionCode:Int, versionName:String) =
setup(applicationId, versionCode, versionName, false)
fun KotlinBuildScript.setupLibrary(applicationId:String) = setup(applicationId, null, null, true)
private fun KotlinBuildScript.setup(
applicationId:String, versionCode:Int?, versionName:String?, library:Boolean
) {
setupPlugins(library)
setupConfiguration(library, applicationId, (versionCode ?: 1) * 2, versionName ?: "1.0")
setupDependencies(library)
}
private fun KotlinBuildScript.setupConfiguration(
library:Boolean, applicationId:String, versionCode:Int, versionName:String
) {
configure<BaseExtension> {
compileSdkVersion(28)
buildToolsVersion("28.0.3")
defaultConfig {
if (!library) {
this.applicationId = applicationId
this.versionCode = versionCode
this.versionName = versionName
}
minSdkVersion(16)
targetSdkVersion(28)
multiDexEnabled = true
vectorDrawables.useSupportLibrary = true
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
}
}
packagingOptions {
exclude("META-INF/LICENSE.txt")
}
lintOptions {
isCheckReleaseBuilds = false
}
if (library) {
defaultConfig.ndk {
abiFilters("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
}
externalNativeBuild {
cmake {
setPath("CMakeLists.txt")
}
}
} else {
flavorDimensions("architecture")
productFlavors {
create("arm") {
dimension = "architecture"
this.versionCode = versionCode - 1
versionNameSuffix = "-arm"
ndk {
abiFilters("armeabi")
}
}
create("x86") {
dimension = "architecture"
this.versionCode = versionCode
versionNameSuffix = "-x86"
ndk {
abiFilters("x86")
}
}
}
}
}
}
private fun KotlinBuildScript.setupPlugins(library:Boolean) {
apply {
plugin("com.android." + (if (library) "library" else "application"))
plugin("kotlin-android")
plugin("kotlin-android-extensions")
plugin("kotlin-kapt")
}
}
private fun KotlinBuildScript.setupDependencies(library:Boolean) {
dependencies {
add("testImplementation", "junit:junit:4.12")
add("implementation", fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
if (!library) {
add("implementation", project(":Library"))
}
add("kapt", "com.google.dagger:dagger-compiler:2.18")
add("implementation", "com.google.dagger:dagger:2.18")
add("kapt", "androidx.lifecycle:lifecycle-compiler:${Version.lifecycle}")
add("implementation", "androidx.lifecycle:lifecycle-extensions:${Version.lifecycle}")
add("implementation", "androidx.lifecycle:lifecycle-common-java8:${Version.lifecycle}")
add("implementation", "javax.inject:javax.inject:1")
add("implementation", "javax.annotation:javax.annotation-api:1.2")
add("implementation", "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${Version.kotlin}")
add("implementation", "org.jetbrains.kotlin:kotlin-reflect:${Version.kotlin}")
add("implementation", "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0-RC1")
}
}
App module gradle:
import Setup.Version
import Setup.setupLibrary
setupLibrary("com.esminis.server.library")
I've found how to solve the problem. Using kotlin dsl you should always set buildFileName property in the settings.gradle of the project.
rootProject.buildFileName = 'build.gradle.kts'
Also, try to delete .idea and .gradle folder and restart Android Studio.

Android productFlavors in gradle-kotlin-dsl

I've experimented gradle-kotlin-dsl in an android project. I'm managed to make it work, but I'm stuck in how to define productFlavors
android {
compileSdkVersion(Config.Android.compileSdkVersion)
buildToolsVersion(Config.Android.buildToolsVersion)
defaultConfig {
minSdkVersion(Config.Android.minSdkVersion)
targetSdkVersion(Config.Android.targetSdkVersion)
versionCode = Config.Version.code
versionName = Config.Version.name
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
}
}
flavorDimensions("dimension")
productFlavors {
//product flavors here
}
}
After some investigation I've got the solution, just use the create method:
productFlavors {
create("flavor1") {
//flavor configurations here
}
create("flavor2") {
//flavor configurations here
}
}
After some investigation I've got the solution, just use the create method, adding here in case someone need it:
productFlavors {
create("flavor1") {
//flavor configurations here
}
create("flavor2") {
//flavor configurations here
}
}

Categories

Resources