[Android SDK] Using variables from Gradle, in Java code

This is a pretty simple issue, but I’ve seen many questions and bad solutions about it.

An example of doing that could be:

file: app/build.gradle

android{
   buildTypes{
       release{
           buildConfigField "int", "SAMPLE_INT", "52"
           buildConfigField "boolean", "SAMPLE_BOOL", "true"
           buildConfigField "String", "SAMPLE_STR", "\"release_foo\""
       }
       debug{
           buildConfigField "int", "SAMPLE_INT", "55"
           buildConfigField "boolean", "SAMPLE_BOOL", "false"
           buildConfigField "String", "SAMPLE_STR", "\"debug_foo\""
       }
   }
}

file: MainActivity.java

@Override
 protected void onCreate(Bundle savedInstanceState){
     String gradleStr = BuildConfig.SAMPLE_STRING;
     int gradleInt = BuildConfig.SAMPLE_INT;
     boolean gradleBool = BuildConfig.SAMPLE_BOOL;
 }

As simple as that 🙂

hope it helps for you!

[Android SDK] Installing Gradle in command-line shell (MacOS X)

Once we install Android Studio (or just gradle itself), it is very comfortable to have it added to our PATH, which makes us able to run commands like

gradle task1

from any Android project’s folder.

One way to do that is adding gradle’s path to our PATH variable. Under MacOS X, this is done with the following steps.

1.- In terminal:

export GRADLE_HOME=/Applications/Android\ Studio.app/Contents/gradle/gradle-2.2.1

*We assume we’re using the bundled Gradle that comes with Android Studio. You can place gradle anywhere else, like your /Users/user folder, and use this location. Example:

export GRADLE_HOME=/Users/jimmy/gradle-2.2.1

2.- Now, let’s have a look at our PATH variable. In terminal:

echo $PATH

It should look like:

/usr/bin:/bin:/usr/sbin: ... (more system folders separated by ":" )

To append gradle’s folder at the end of our path:

export PATH=$PATH:$GRADLE_HOME/bin

Now, execute “echo $PATH” again, and you should see gradle’s folder appended in the end, separated by a “:”.

If you were successful on step 2, you should now be able to execute:

gradle –version

And see an output like:

------------------------------------------------------------
Gradle 2.2.1
------------------------------------------------------------
Build time:   ...
Build number: none
Revision:     6fcb59c06f43a4e6b1bcb401f7686a8601a1fb4a
Groovy:       2.3.6
Ant:          Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM:          1.6.0_65 (Apple Inc. 20.65-b04-462)
OS:           Mac OS X 10.9 x86_64

Hope it helps!