Reading an environment variable from Android build.gradle

Have you ever had the need to read an external variable like an environment variable from your Android build.gradle file?

On a recent project of mine we needed to enable our QA engineers to specify different login urls (for dev, staging, production, etc) to run our test automation against.  The idea is that they would set a specific environment variable, ‘ANDROIDDOMAIN’ in this case, and our build script would read in this variable and add it to the BuildConfig class, which we then reference via our test.

Below is the code that reads in the environment variable:

As you can see, here we look for the environment variable named ‘ANDROIDDOMAIN’, and if it is present we print it out and return it from this method.

The next code snippet shows how to add the result of the ‘getAndroidDomain()’ call to the BuildConfig class (in this case we add to the BuildConfig debug class:

Now in our test class we can access the ‘TEST_ANDROID_DOMAIN‘ field on this class, like so:

Do you have a better way of doing this?  Let me know!

Kotlin for Android: new project

For this tutorial, I’m going to walk you through a sample project that gets you set up for development in Kotlin for Android, using Android Studio and the Kotlin plugin.

Create a new project

As you would normally do with a Java-based Android application, create a new project in Android Studio by choosing ‘Start a new Android Studio project’:

Start a new Android Studio application
Start a new Android Studio project

or if you already have a project open, go to ‘File > New Project’:

New Project
File > New Project

Give your project a name.  I gave mine the name ‘FirstKotlin’:

First Kotlin
I named mine ‘FirstKotlin’

Choose the defaults on the next screen.  Mine looked like this:

Target Android Devices

On the ‘Add an Activity to Mobile’ dialog, choose ‘Basic Activity’:


On the ‘Customize the Activity’ screen, just leave the defaults:


Click finish to create the project.

Run the application

After your project is created, go ahead and run it to make sure that you have a working application.

running app
running app

Download Kotlin plugin

Pull up Android Studio preferences (Android Studio > Preferences…).  Go to Plugins in the left navigation, and search for ‘Kotlin’.  Install this plugin.

kotlin plugin
kotlin plugin

Modify application build.gradle to add Kotlin plugin as a dependency

Add classpath org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.6 as a dependency to your application’s root build.gradle file.  My full application build.gradle is below:


Modify module build.gradle to apply Kotlin plugin

Add these two lines to your module’s build.gradle.  My module’s build.gradle is found at app/build.gradle:

Full build.gradle is found below:

Convert default to Kotlin

Now here’s the fun part.  Let’s convert the file to Kotlin.  Open the file (mine’s at app/src/main/java/com/devdustin/firstkotlin/  Then, go to Code > Convert Java File to Kotlin File:

convert java to kotlin
convert java to kotlin

Your converted class should look something like this:


Run the application

Now, run your first Kotlin app!

running app
running app

If you get the same result as from before converting your Java file to Kotlin, good job!

Kotlin vs Java analysis

What differences do you notice between Kotlin and Java?

Here are a few to pay particular attention to:

  • Override as a keyword, not an annotation: in Java, the @Override annotation is used to indicate the developer’s intention in overriding a method, and if not properly overridden, will cause a compile time check. But it’s not required (though you’ll likely get a compiler error, depending on the compiler you’re using).  In Kotlin, you are required to use it.
  • Primary and secondary constructors: shown in the class above only as a primary constructor in ‘AppCompatActivity()‘, Kotlin classes have a unique way of handling object construction.  I’ll dig into this more in future posts.
  • Null Safety: one of the goals of the Kotlin type system is to avoid NullPointerException from occurring.  The ‘?’ after Bundle indicates that savedInstanceState could potentially be null.  You can also expect future posts on this topic, as it’s key to understanding Kotlin.
  • ‘fun’ indicates function: Kotlin uses the ‘fun’ keyword to indicate what would be a method in Java.
  • ‘extends’ and ‘implements’ are represented using a colon: very much like C# and other modern languages.
  • Semicolons are optional: though you can add them if you’d like to.
  • Function parameters are written ‘backwards’ compared to Java: they are defined using Pascal notation: name: type, and are separated using commas. A type is required for each parameter.


In this sample Android project you get a taste of what it’s like to develop with Kotlin. The Kotlin plugin for Android Studio includes a great tool for converting Java files to Kotlin, which helps developers ease into developing with Kotlin.

I went over a few language features that are expressed in this simple example.  Future posts will touch more in depth on these and many other Kotlin topics, with an emphasis on Android development.

What does the ‘which’ command do?


The ‘which’ command is great for finding where a program that exists in the user’s path is located.

To use it, type the following in a terminal:

What prints out on the next line is the first location found where that program is installed.

There are options available, see below:

Genymotion device goes offline after Mac screen locks

Have you ever had your Genymotion device go offline after locking your Mac screen?

After debugging in Android Studio, locking my Macbook Pro screen, and then logging back in, frequently my Genymotion device will show as [OFFLINE] to the Android Studio debugger.  It’s really an inconvenience, as restarting the device and app often take a while.

If so, rather than restart the device  completely, try this from a terminal window:

Give adb a moment to restart, then issue this command:

Once adb has restarted, you’ll see your device listed, like below:



Note: if you get ‘command not found’ after typing ‘adb’, then it must not be on your PATH.  Add ‘ANDROID_HOME/platform-tools’ to your PATH environment variable.  The location of ‘adb’ on my machine (after typing ‘which adb’) is ‘/Users/dustinkendall/Library/Android/sdk/platform-tools/adb’

Hope this helps!

Kotlin vs Java: performance

How does Kotlin performance compare to Java’s?

One of the questions you’re bound to have when switching over to Kotlin is whether or not it is faster than Java.

While an application’s performance is highly dependent on its OS, runtime, and the actual code, in general Kotlin will perform very similarly to Java.

JetBrain’s kotlin compiler produces JVM bytecode.  While I’m not going to an analysis of the bytecode that it produces, from the research I’ve done it appears that it is very similar (at least in the performance sense) to the bytecode that Java compiles to.


While the question posed in this blog post is definitely a common one, it’s a bit too simplistic.  Much of how an app performs is dependent on the actual code that you write and the algorithms and data structures that you choose to use.

Kotlin has a distinct advantage over Java in this arena, because it provides us with implementations of certain programming patterns.  These patterns are highly efficient and likely to be less buggy than if you were to roll your own.

Take Kotlin Data Classes for example

You get this construct for free in Kotlin.  In order to do the same thing in Java, you have to write all the boilerplate code yourself.   This introduces the potential for that code to be buggy and inefficient.  Not good.

Joshua Bloch’s Effective Java describes the Immutable Object pattern.  Kotlin Data Classes are a great implementation of this pattern.  And you get it for free, built into the language.


Comparing Kotlin’s performance to Java’s is a common question that many have before switching from Java to Kotlin.  Kotlin compiles to JVM bytecode and the bytecode it produces is very similar to Java’s.  There is no reason that Kotlin should be slower than Java when comparing equivalent code.

Comparing speed of languages is less important than the data structures and algorithms used by the developer.  Kotlin provides some great built-in patterns that result in cleaner, easier to read, and less buggy code.

wc word count command


What is the wc command in Unix-like operating systems?

Have you ever had the need to count the words in a text?

If you’re like me, you’ve probably used an online word counting tool, like the one found here.

But who likes copying and pasting to a website when you have such great tooling available via terminal?

Check out the wc command.  Usage: wc [-clmw] [file …]

Here is an example:

See below for more usage options:

Introduction to Kotlin for Android


What is Kotlin?

Kotlin is a programming language that purports to be 100% interoperable with Java. Created by JetBrains — the company that created IntelliJ IDEA, WebStorm, and others. JetBrains released the first version in 2011, reportedly after one year of development. The 1.0 release of the language happened on February 15, 2016.

Kotlin is an Open Source language, developed on Github ( under the Apache 2.0 Open-source license. As of this post, there are 139 contributors to the project.

Why develop with Kotlin?

  • Safe — for example, null references are controlled by the type system
  • Concise — reduces a lot of boilerplate code
  • Versatile — build Android apps, front-end code, and server-side applications
  • Interoperable — with frameworks and libraries of the JVM
  • Easy to read and learn — less verbose than Java
  • Great tooling — Java-to-Kotlin converter, command-line compiler

Kotlin advantages and features

  • Lambda expressions
  • Extension functions
  • Null-safety
  • Smart casts
  • String templates
  • Properties
  • Primary constructors
  • First-class delegation
  • Type inference for variable and property types
  • Singletons
  • Declaration-site variance and Type projections
  • Range expressions
  • Operator overloading
  • Companion objects
  • Data classes
  • Separate interfaces for read-only and mutable collections

Projects that use Kotlin

Why is Kotlin good for Android development?

Oftentimes in Android you’ll get crashes due to NullPointerException. As null references are controlled by the type system in Kotlin, you are much less likely to come across them.

Less crashes == happier customers == better app ratings.

Jake Wharton has a post that describes some advantages Kotlin brings to the table for Android.


Kotlin is a great new language replacement for Java.  It’s very popular in the Android development community, and can be used for back-end server-side development, as well as front-end development.

Try it out for yourself with the online demo IDE:

Spring Autowired annotation

In my previous post I briefly introduced the concept of Spring’s @Autowired annotation. This post goes more in-depth about this annotation, and its importance when developing with the Spring framework.

Spring uses the @Autowired annotation when it determines where it needs to inject a given @Bean. You can see this in the example below:

This example uses @Autowired on a private member variable referenced via class. In this example, the @Component is on the WeatherService class. The DependencyInjectionWithSpring class references the WeatherService class directly. I’ve annotated this reference with the @Autowired annotation. Spring then knows that it needs to find a bean (component) that matches. In this case, it finds the WeatherService class and injects it into the DependencyInjectionWithSpring class.

You can also reference with @Autowired via interface:

Here, I change the WeatherService class to be named WeatherServiceImpl, and have it implement the WeatherService interface, which I’ve also defined. DependencyInjectionWithSpring now references this interface (WeatherService), and the @Autowired annotation stays. Spring then knows that it needs to find a bean/component that implements the WeatherService interface. It finds the WeatherServiceImpl class and injects it into the DependencyInjectionWithSpring as a dependency (weatherService).

Field X in Y required a single bean, but 2 were found

What happens if we have multiple beans (components) that implement the same interface? Like this:

Both SunnyWeatherServiceImpl and CloudyWeatherServiceImpl implement the WeatherService interface. The DependencyInjectionWithSpring class depends on an implementation of WeatherService. Both of these classes would work, since they implement that interface. Spring is aware and manages both of these classes, since they are annotated with the @Component annotation. How does Spring know which one to choose? Let’s run the application and see what happens:

The application is unable to start. Spring can’t determine which bean to set for the weatherService.

How do I fix this?

To resolve this issue and tell Spring which bean to use in this situation, we have a few options.

The first option is to follow the first suggestion given in the exception:

Consider marking one of the beans as @Primary…

The @Primary annotation can be used to indicate to Spring which bean to use. In this case, I add the @Primary annotation to the SunnyWeatherServiceImpl:

Now when I run the application, it starts up with no errors and runs as expected, injecting the SunnyWeatherServiceImpl (the one with the @Primary annotation) into the DependencyInjectionWithSpring class.

There’s another option that Spring gives us, as mentioned in the error message from above:

or using @Qualifier to identify the bean that should be consumed

@Qualifier is a Spring annotation that allows us to tell Spring which bean we want to inject. See below:

Pay particular attention to the DependencyInjectionWithSpring class. The weatherService dependency in this class is now annotated with @Qualifier(value="cloudyWeatherServiceImpl"). This tells Spring to use the cloudyWeatherServiceImpl bean when injecting this dependency.

Now when I run the application, again it starts up with no errors and runs as expected. This time, I told Spring to use the cloudyWeatherServiceImpl class and it prints out The weather is cloudy with a 90% chance of rain as expected.

There’s yet another way to indicate to Spring which bean to inject. This is by naming the variable of the dependency the name of the class we want to inject. Like so:

Here, the WeatherService interface gets the name cloudyWeatherServiceImpl. This tells Spring that I want to inject the bean with the name cloudyWeatherServiceImpl. When I run this code, the application again starts up with no problems, and I again get the expected output.


Spring’s @Autowired annotation is used to indicate where to inject a Spring-managed bean. The @Primary annotation allows us to indicate which bean to use when multiple beans that match are present. The @Qualifier annotation allows us to specify a specific bean to inject on a given dependency. Finally, we learned that we can name the dependency with the bean name to also specify which bean to inject.

Dependency Injection using Spring

This post describes the basics of how to do dependency injection with the Spring framework. If you are unfamiliar with dependency injection, you may want to check out my first post on dependency injection before continuing.

Let’s start of with an example

Here we have two classes – DependencyInjectionWithSpring and WeatherService. WeatherService is a dependency of DependencyInjectionWithSpring. DependencyInjectionWithSpring instantiates WeatherService. Its run() method calls the printWeather() method on WeatherService. Pretty simple stuff.

Can you spot the problem? Take a minute and look at DependencyInjectionWithSpring. This class instantiates the WeatherService class, and sets this object to its private member variable weatherService. This is not a problem per se, or rather not compile time or even a runtime problem. This code still compiles. It still runs. It still produces the result we are trying to achieve.

I don’t see any problems with this, can you explain?

Here are a few

  1. Testability – you can’t test DependencyInjectionWithSpring without testing WeatherService as well. What if weather service gets its data from a thermometer or some external system? You wouldn’t want to wait for the service to run for your tests to complete, that could take a while. Unit tests should run fast. Also, you don’t have control over what WeatherService returns. Since you don’t have this control, how can you test for certain conditions, like returning null or throwing an exception.
  2. Reusability – as in the Testability problem, you can’t reuse DependencyInjectionWithSpring without getting WeatherService. This limits how and where we use this class, since wherever we have DependencyInjectionWithSpring we get WeatherService. What if we wanted different behavior than what WeatherService provides? We can’t in this case.
  3. No configuration without recompilation – what if we wanted to change the implementation of WeatherService? What if, instead of reading the weather from a thermometer we wanted to read it from a web service instead? In our current implementation, we are stuck. We would have to write code to change WeatherService to another implementation, recompile, and redeploy. As mentioned before, if we intend to use DependencyInjectionWithSpring we automatically get the WeatherService implementation with it. In other words, they are highly coupled.

So how does Spring help?

Here’s where the Spring framework can help us out.

The Spring framework is known as an IOC container. An IOC container serves two main purposes:

  1. Manage creation (and full lifecycle) of objects to be used in a system.
  2. Configure coupling of components. Spring provides (or injects) the objects it manages to the classes that depend on these objects.

For #1, that means we can get rid of the new WeatherService() piece. Like this:

If you try to run this, you’ll get a NullPointerException because weatherService has not been instantiated.

How does Spring fix this?

Since Spring is an IOC container it can instantiate objects on our behalf. The objects that get instantiated are known as Beans in the Spring framework. The way that you flag a class that you want Spring to be aware of (that is, you want it to be a Spring bean) is through the @Component annotation, like this:

This annotation lets Spring know that it should create and manage the lifecycle of this object.

However, if we run our code now, we’ll still run into a NullPointerException. Why is this so?

That’s where #2 from above comes into play. The Spring Framework also configures how components are coupled together. It injects objects into the classes that depend on them.


Spring injects objects via the @Autowired annotation. There are multiple ways that @Autowired can be used. To keep things simple, we’ll annotate a private member variable with @Autowired, and let Spring inject it for us. See below:

Pay particular attention to lines 23-24. This is where the WeatherService dependency gets injected into DependencyInjectionWithSpring.

Now, when we run it, we no longer see a NullPointerException, and the text The weather is sunny with a 20% chance of rain gets printed out, as expected.

To reiterate. Spring instantiates the weatherService for us. It also injects it where requested (via the @Autowired annotation).


If you notice in the gist above, and if you run the code, you’ll see that this application is not a web application, but a command line application. In particular, take a look at line 21 above implements CommandLineRunner. CommandLineRunner is an interface from Spring Boot that has one method with the following signature: public void run(String... args) throws Exception. In this example, our DependencyInjectionWithSpring class implements this interface, and in the run method calls the weatherService.printWeather() method.


In this post I described the basics of dependency injection with the Spring framework. Project examples can be found on my Spring Beginner Tutorial on github.