Create properties file using gradle - android

I would like to create a properties file named "dev.properties" using gradle. Here is my build.gradle code:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.8.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
android {
compileSdkVersion 16
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 16
targetSdkVersion 16
}
def prop = new Properties()
def propFile = new File("dev.properties");
propFile.createNewFile();
prop.store(propFile.newWriter(), null);
buildTypes {
release {
runProguard false
proguardFile getDefaultProguardFile('proguard-android.txt')
}
}
}
The file is created when I right click on the build.gradle and choose run. However it's not created when I make the entire project. How come?
I'm using android studio 0.4.6 with gradle 1.10.

It's creating the file, just not where you expect. Your script is creating the file inside the current working directory, and in Android Studio, that will be in Android Studio's distribution. There's a bug filed to make Android Studio consistent with the command line (https://code.google.com/p/android/issues/detail?id=65552) and put the working directory at the project root (well, that's assuming your working directory is set there when you issue Gradle commands), but the fix is actually difficult, and the real answer is you should probably never implicitly rely on the working directory, so that you can make your builds as bulletproof as possible.
If you do something like this:
def propFile = new File("${project.rootDir}/dev.properties")
it will put the file in your project's root directory. There's also project.projectDir, which will be your module directory; see http://www.gradle.org/docs/current/dsl/org.gradle.api.Project.html for more details on what's available to you.
As a side note, you should keep in mind this will run every time the build file is evaluated (because the android block is executed every time the build script is run), which could be more often than you want. It's more than just build time; it's project import time as well, and any time Android Studio decides to evaluate the build file, which happens when you open the project and also when you click the Sync Project with Gradle Files button.
Additionally, you should consider at what phase of the build process you want it to happen: is it script evaluation time, or do you want it to run after Gradle has done its analysis and is ready to actually start building things? You can read http://www.gradle.org/docs/current/userguide/build_lifecycle.html to find out more about that.
Sorry, I know it's a lot of information to drop on you when you're just trying to get something going, but those concepts will help you out pretty soon down the road.

Related

Unable to switch to debug build variant in Android Studio

I've switched to release build variant and configured signingConfigs. Now when I try to check the debug build variant from the drop down menu it switches immediately back to the release build variant. So I'm not able to run my app in debug mode any more.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'
android {
signingConfigs {
config {
...
}
}
compileSdkVersion rootProject.compileSdkVersion
buildToolsVersion rootProject.buildToolsVersion
defaultConfig {
applicationId "com.kost.foo"
minSdkVersion rootProject.minSdkVersion
targetSdkVersion rootProject.targetSdkVersion
versionCode 2
versionName "1.1"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk {
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
}
externalNativeBuild {
cmake {
...
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable true
signingConfig signingConfigs.config
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
main {
jniLibs.srcDirs = ['src/main/jni']
}
}
externalNativeBuild {
cmake {
path 'src/main/jni/CMakeLists.txt'
}
}
}
kapt {
generateStubs = true
}
repositories {
maven { url 'https://github.com/linchaolong/stetho-realm/raw/master/maven-repo' }
mavenCentral()
}
I've tried to revert all changes in build.gradle as it was before configuring, but with no luck.
Any ideas how to fix the issue?
I had a similar problem where most of the Build menu items were greyed out.
'Sync project with Gradle files' didn't fix.
I noticed a 'Build Variants' toggle button on the bottom left of Android Studio (v 3.1.2) and with this was finally able to choose the variant I needed.
Maybe this will work for you too.
Maybe you have got your solution to this, just in case, i provide my solution here.
For Android Studio 2.x
It may because that you compile your dependent project using:
compile project('module_a')
Above setting will force your project to compile the release version of your modules. Just change it to below:
releaseCompile project(path: ':module_a', configuration: 'release')
debugCompile project(path: ':module_a', configuration: 'debug')
For Android Studio 3.x
You don't need to explicitly specify the build variant for a "module project". Just using
implementation project(':library')
will automatically help select the correct build variant.
Here is a detailed explanation: https://developer.android.com/studio/build/?utm_source=android-studio#variant_aware
For Android Studio 3.x Upgraded from 2.x
Delete the .idea folder under your project root directory and restart your Android Studio.
Below is the GUI screenshot:
Hope it helps!
Just need to cut ".idea" Folder and paste it outside Project root folder( For Back up if you need).These files will be auto regenerated. On Opening the project it"ll ask add module (app) to your project. You can ignore the same.
It set set default build variant to be "debug".
You can see build variant tab on left corner or hover on "Monitor" Symbol on left bottom to get build variant option.
I just had the same issue. Solved it by closing Android Studio, removing the generated files and folders: .gradle, .idea, app/.externalNativeBuild, app/build, build, app/app.iml, ProjectName.iml, local.properties, then relaunching Android Studio and allowing it regenerate all these files from scratch.
Had the same problem, solved creating a new temporary Build Type, Build > Edit Build Types, select Build Types and add a new one. Sync, then you can select the new build type, and then revert back to original Debug build type.
Open your module setting. (Click F4)
Go to build types and create a new Build by clicking on plus(+) sign.
Name it anything, like "demo".
Duplicate all the data of debug build.
Now when you open Build Variant you will be able to switch to Debug as well as Demo.
For me I was unable to switch to our 'devDebug' variant but I could switch to another variant like 'devRelease' and then 'devDebug'. So try switching to another variant first.
I ran into a similar issue. My module level build.gradle reflected configurations specified for "debug" AND "release" accordingly. I was able to successfully run my app on emulator and device (LG) prior To Building and Signing My Release Version Of My App. After Building and Signing The Release Version and attempting to Run The Signed APK on My Phone and Device, i received an Error PM Session 'mobile': Error Launching activity....Error while Launching activity..So I started retracing my steps and realized that before deploying the signed release variant, i opened up the run/debug Configurations Dialog
and mistakenly selected the the Value APK from app bundle value From The Deploy attribute, under the Installation category
I Signed My APK In its ENTIRETY and NOT Via Bundle, so the option selected was attempting to Deploy an invalid App Bundle That Was Never Generated To Begin With, even if it was for the correct Build Variant.
I have this question too. My solution is checkout to the branch which i had changed the build variants. And at that branch, I can change from release back to debug. Then just checkout to current branch and everything is OK. It seems to be a Android Studio bug.
English is not my native language; please excuse typing errors.
I also meet this situation. i do this to solv .
Solv:
1. delete each module's impl suffix type file and build folder;
2. then click this button to sync project with gradle build file. button position
finally. and then this problem will be fix.
I fixed this issued by:
Add a new build type named debug1 via edit build.gradle;Enable debug function of this build type;
Sync and select the new build type debug1;
This issue seems to occur when opening the project in a symlinked location on linux. Opening the project directly fixed this issue for me.
relevant link: https://issuetracker.google.com/issues/156857164
For me, it was an issue with the gradle version. Make sure your plugin version and the required gradle version fit together, as defined here.
https://developer.android.com/studio/releases/gradle-plugin
You can find out which gradle versions you are using under:
File -> Project Structure... -> Project
I tried all the above to no effect. Eventually stumbled across File > Invalidate Caches/Restart... for other reasons and found it worked for me.
in main root of app in build.gradle
replace it from:
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
}
to my Android Studio v3.0.1 in my case:
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
March 26, 2021:
Would not switch from Release to Debug,
File | Invalidate Caches fixed it for me
Unrelated to your build.gradle file,
Sharing hoping it might help someone else -
I was having similar issue it was because one of the line in build.gradle -
android {
...
publishNonDefault true // remove this line and it should work!
}
Here you can get more detail about publishNonDefualt -
It is also possible to publish all variants of a library. We are planning to allow this while using a normal project-to-project dependency (like shown above), but this is not possible right now due to limitations in Gradle (we are working toward fixing those as well).
Publishing of all variants are not enabled by default. The snippet below enables this feature:

Android Studio 1.3 test module (com.android.test) [duplicate]

I'm attempting to set up a unit test module as described in the android studio blog post. However, doing a gradle build fails telling me "Configuration with name 'debug-classes' not found". Debug is the name of the targetVariant it's trying to build, but I don't understand what is going wrong here.
Here's my test module's gradle file.
apply plugin: 'com.android.test'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
targetProjectPath ':app'
targetVariant 'debug'
}
This is the blogpost describing the new test module functionality.
http://android-developers.blogspot.com/2015/07/get-your-hands-on-android-studio-13.html
I'm using the Gradle plugin v1.3.0
I was also curious about separating app code and test code and i had hard time to figure it out. I look at the stack trace and found the DependencyManager (line 238) having a TODO to fix that in gradle.
1) You are right about the build flavors.You have to enter the correct variant
targetVariant '<flavor>Debug'
e.g.
targetVariant 'flavor1Debug'
2) You also need to change you targetProjectPath's module build.gradle. Add the following snippet:
android {
// ...
publishNonDefault true
// ...
}
which publishes all build variants! It its disabled by default due to some limitations of gradle.
Here is a sample app that works https://github.com/googlesamples/android-testing-templates/tree/master/AndroidTestingBlueprint
You must use
buildToolsVersion = '23.0.0rc3'
And of course
publishNonDefault true

Android Gradle Issue

I know there are 100's of questions/answers around this topic, but none of them seem to give me an answer. I know some(if not all) of my problems are around my lack of understanding of gradle in general. BUT, i'm hoping for some help.
I've got my project working just fine on my desktop. I'm traveling this week, and wanted to work on it some on my laptop. I have all the files, and have the same version of Android Studio on both machines. I kept getting all kinds of gradle errors when opening my project. I think I've went on several wild goose chases at this point.
So I decided to step back and just create a NEW basically blank project in Studio. That ALSO has all kinds of gradle issues. I tried uninstalling Android Studio and re-insatlling, and still no dice even getting a basic project to not give the gradle errors.
I am getting
11:12:27 PM Gradle 'MyApplication' project refresh failed:
A fatal exception has occurred. Program will exit.
: Gradle settings
As the error.
Below is my two gradle files.
Top Level File(which was blank in my actual project, but has something in it in the default one)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.7.+'
}
}
allprojects {
repositories {
mavenCentral()
}
}
The next build file
apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 7
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile 'com.android.support:support-v4:18.0.0'
}
I am using Android Studio 0.4.2
I am at a complete loss of what is going on. I think it could be that Studio is not actually recognizing that this is an android project. I tried some of the gradlew.bat commands and I got an error mentioning that it does not like the "apply plugin: 'android'" entry. But, I have no idea why that would be.
Any thoughts on where I should start would be greatly appreciated. I have no ideas of where to go next, and guessing at it anymore is not an option.
I've got the same issue with IntelliJ IDEA(which Android Studio is based on) on my laptop and found a solution here: https://code.google.com/p/android/issues/detail?id=65219
Set File -> Settings -> Compiler -> Java Compiler -> Additional command line parameters
-Xms256m -Xmx512m
File -> Settings -> Compiler -> Gradle -> VM Options
-XX:MaxHeapSize=256m -Xmx256m
and in YourAppName/build.gradle update dependencies to use newer gradle version
classpath 'com.android.tools.build:gradle:0.9.+'
Then restart Android Studio and everything should be fine. Otherwise you can take a look at full log file by going to Help -> Show Log in Explorer
To add a little more knowledge to the 'Gradle XXXX project refresh failed'
.
Adding following line to
File -> Settings -> Compiler -> Gradle -> VM Options:
-Xmx256m
seems to solve the problem.
.
It is worth noting that it fixes only certain cause of the problem - and there may be many. In my case: the machine I'm using is 32-bit and has very little memory. As a result my compiler couldn't reserve enough memory on the heap and so refused to compile.
Therefore if you don't have much RAM try adding the above line.
If still stuck, try:
https://stackoverflow.com/a/21168562/3508719
Did you verify that you have buildToolsVersion 19.0.1 and compileSdkVersion 19 is available on you machine, since you are working on laptop I believe this is new setup.
Can you go to Tools -> Android -> SDK Manager and see if you need to install any version specified in your gradle script. Or update gradle script as per SDK and build tools you have.
My couple of issue were resolved by updating SDK and tools!

Android Studio Gradle Build Flavors

I am having troubles understanding Build Flavors in Android Studio. I am trying to achieve a simple thing: buidling 2 signed APK's with a minor code change. The "pro" APK just has a different drawer.xml in res/layout/. I've read a few things in the Documentation and here on StackOverflow but I don't see anything happen with my build.gradle changes.
my current build.gradle file:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.+'
}
}
apply plugin: 'android'
dependencies {
compile files('libs/android-support-v4.jar')
compile files('libs/GoogleAdMobAdsSdk-6.4.1.jar')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 14
targetSdkVersion 17
}
productFlavors {
lite {
packageName = 'com.mikebdev.refuel'
}
pro {
packageName = 'com.mikebdev.refuelpro'
}
}
sourceSets{
android.sourceSets.pro {
res.srcDirs = ['src/main/res_pro']
}
}
}
I created a new folder:
/src/main/res_pro/layout/drawer.xml
What am I doing wrong here?
EDIT
I updated my build.gradle file above.
After resetting my whole Android Studio because of some other instabilities I am now able to choose in the bottom left corner my build variants (lite-debug, lite-release, pro-debug, pro-release) Why even those debug AND release variants?
This seems to work now as it should.
I added a answer below
After resetting my whole Android Studio because of some other instabilities I am now able to choose in the bottom left corner my build variants (lite-debug, lite-release, pro-debug, pro-release) Why even those debug AND release variants?
I created a whole new Project with Module and copy&pasted everything from my old project which I exported from eclipse a while back in there.
NOW it works.
My Android-Studio was kinda broken before my reinstall. More crashes than there should be, some strange behaviors ans such stuff.
What you're doing wrong is that you are putting your file in /src/main/res_pro/layout/drawer.xml and not setting it in the gradle. the default location for the flavor that you created would be:
/src/pro/res/layout/drawer.xml
With this build script you are using build types AND flavors. For changing the xml file you only need the flavors. Try to delete buildTypes and use the productFlavor block as child of android.
The changing of the res folder of the pro flavor should go into the sourceSets Block right after all the changes of the main sourceSet

Exclude a class from the build in Android Studio

I've been learning Android over the past few months and have been using Eclipse v4.2 (Juno) as my IDE.
I am trying to migrate to Android Studio. How can I exclude some of the classes from build path I have yet to complete?
In Eclipse, it was a straightforward right click. I can't find any reference to it in Android Studio.
AFAIK, IntelliJ allows to exclude packages. Open Project Structure (Ctrl + Alt + Shift + S in Linux) → Modules → Sources tab.
However, if you would like to exclude only one class, use the Gradle build file.
Android Studio uses Gradle, so in the build.gradle file, add a custom SourceSet inside the android configuration that excludes your class, e.g.:
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
defaultConfig {
minSdkVersion 19
targetSdkVersion 19
packageName "org.homelab.lab"
testPackageName "org.homelab.lab.test"
}
sourceSets {
main {
java {
exclude '**/SomeExcludedClass.java'
}
}
androidTest {
java {
exclude '**/TestSomeExcludedClass.java'
}
}
}
}
It works fine with Android Studio v3.0:
apply plugin: 'com.android.application'
android {
defaultConfig {...}
buildTypes {...}
sourceSets {
main {
java {
exclude 'com/example/full/package/path/MainActivity.java'
}
}
}
}
It can't be done.
Maybe it could back in May 2013 when the accepted answer was provided, but not anymore (as of Android Studio 1.2).
Here is the issue: Sourceset component should be more like the Java one
According to the labels they are targetting Android Studio 1.5 for adding these feature.
Cross posting from https://stackoverflow.com/a/69261642/3689782 but it seems useful to repeat here.
I came across a way to make this work specifically for Android unit tests (but I'm assuming it's adaptable) using a combination of other solutions from the link above:
def filesToExclude = [
'**/*TestOne*.kt',
'**/*TestTwo*.kt',
...
]
tasks.withType(org.gradle.api.tasks.SourceTask.class).configureEach {
it.exclude(filesToExclude)
}
android.sourceSets.test.kotlin.exclude(filesToExclude)
In my particular case, the extra wildcards around the test name were needed due to other generation occurring (specifically, Dagger with kapt).
This seems to be a bit hacky way to approach it, but it works by ensuring the test target is excluded from all tasks that it could actually be excluded from (including both build & kapt tasks). The sourceSets exclusion is still necessary for the file not to be picked up for compilation (I think this is the Kotlin Gradle Plugin doing it, but it might also be Android Gradle Plugin--I'm not well versed enough in debugging Gradle builds to pin it down).
The way I used to do the same was by,
For Windows: Right click on the Java file → Show in Explorer → change extension of the file from '.java' to '.c'.
For Mac: Right click on the Java file → Reveal in Finder → change the extension of the file from '.java' to '.c'
It is as simple as that.
For my case I need to prevent a whole folder then I did it by this -
sourceSets {
main {
jniLibs.srcDirs = ['libs']
java {
exclude 'com/example/myfolder'
/* The holder name I want to excludes its all classes */
}
}
}
Move it to a new folder.
Right-click → Show in explorer → cut and then paste to a new folder (outside of any project).
I just created a new folder inside of AndroidStudioProjects folder and placed them there.

Categories

Resources