Learning Kotlin by building Android Applications

3.9 (8 reviews total)
By Eunice Adutwumwaa Obugyei , Natarajan Raman
  • Instant online access to over 8,000+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Setting Up for Android Development

About this book

Today Kotlin is an official programming language for Android development and is widely adopted. Kotlin is expressive, concise, and powerful. It also ensures seamless interoperability with existing Android languages like JAVA and C++, which means that it's even easier for developers to use.

This book adopts a project-style approach, where we focus on teaching Android development by building three different Android Application: a Tic-Tac-Toe application, a location- based alarm and a To-Do list application.

The book begins by giving you a strong grasp of the Kotlin language and its APIs as a preliminary to building stunning applications for Android. You'll learn to set up an environment and as you progress through the chapters and the building of the different applications, the difficulty level will steadily grow.

The book also introduces you to the Android Studio IDE, which plays an integral role in Android Development. It covers Kotlin's basic programming concepts such as functions, lambdas, properties, object-oriented code, safety aspects and type parameterization, testing, and concurrency, and helps you write Kotlin code to production.

Finally, you'll be taken through the process of releasing your app on the Google Play Store. You will also be introduced to other app distribution channels such as Amazon App Store.

As a bonus chapter, you will also learn how to use the Google Faces API to detect faces and add fun functionalities.

Publication date:
June 2018
Publisher
Packt
Pages
316
ISBN
9781788474641

 

Chapter 1. Setting Up for Android Development

Java is one of the most widely used languages worldwide and, until recently, was the language of choice for Android development. Java, in all its greatness, still has some issues. Over the years, we've seen the evolution of a number of JVM languages that have tried to fix the issues that come with Java. A quite recent one is Kotlin. Kotlin is a new programming language developed by JetBrains, a software development company that produces software developer tools (one of their products is IntelliJ IDEA, which Android Studio is based on).

In this chapter, we'll take a look at:

  • What makes Kotlin great for Android development
  • What you need to be ready for Android development
 

Why develop Android with Kotlin?


Of all the JVM languages, Kotlin is the only one that offers a lot more to Android developers. Kotlin is the only JVM language, other than Java, which offers integrations with Android Studio.

Let's take a look at some of Kotlin's amazing features.

Concise

One of Java's biggest issue is verbosity. Anyone who has ever tried writing a simple hello world program in Java will tell you the number of lines of code that requires. Unlike Java, Kotlin is not a verbose language. Kotlin eliminates a lot boilerplate code such as getters and setters. For example, let's compare a POJO in Java to the same POJO in Kotlin.

Student POJO in Java:

public class Student {

    private String name;

    private String id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

Student POJO in Kotlin:

class Student() {
  var name:String
  var id:String
}

As you can see, there's way less Kotlin code for the same functionality.

Say bye bye to the NullPointerException

One of the major pain points with using Java and a number of other languages has to do with accessing a null reference. This can result in your application crashing without showing the user an adequate error message. If you're a Java developer, I'm pretty sure you're well acquainted with the almighty NullPointerException. One of the most amazing things about Kotlin is null safety. 

With Kotlin, a NullPointerException can only be caused by one of the following:

  • An external Java code
  • An explicit call to throw the NullPointerException
  • Usage of the !! operator (we'll learn more about this operator later)
  • Data inconsistency regarding initialization

How cool is that?

Java interoperability

Kotlin is developed to be able to work comfortably with Java. What this means for developers is that you can make use of the libraries written in Java. You can also work with legacy Java code without worry. And, the fun part about it is you can also call Kotlin code in Java.

This feature is very important for Android developers because, currently, Android APIs are written in Java. 

 

Setting up your environment


Before beginning your Android development journey, there are number things you have to do to make your machine Android developer-ready. We'll go through them in this section.

Note

You can skip this section if you're not new to Android development.

Java

Since Kotlin runs on the JVM, we have to make sure that our machine has the Java Development Kit (JDK) installed. If you do not have Java installed, skip to the section on installing the JDK. If you're not certain, you can follow the following instructions to check the version of Java installed on your machine.

On Windows:

  1. Open the Windows Start menu
  2. Under the Java Program listing, select About Java
  3. A popup will show, with details about the version of Java on the machine:

On a Mac or any other Linux machine:

  1. Open the Terminal app. To do this, open launchpad and typeterminalin the search box. The Terminal app will show up as shown in the following screenshot. Select it:

  1. In Terminal, type the following command to check the JDK version on your machine: java -version
  2. If you have the JDK installed, the version of Java will be displayed as shown in the following screenshot:

Installing the JDK

  1. Open your browser and go to the Java website: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Under the Downloads tab, click on the Download button under the JDK, as shown in the following screenshot:

  1. On the next screen, select the Accept License Agreement checkbox and click on the download link for the product that matches your operating system
  2. When the download is complete, go ahead and install the JDK
  3. When the installation is complete, you can run the version check command again to be sure your installation was successful

Android Studio

A number of IDEs support Android development, but the best and most used Android IDE is Android Studio. Android Studio is based on the IntelliJ IDE (developed by JetBrains). 

Installing Android Studio

Go over to the Android Studio page, https://developer.android.com/sdk/installing/studio.html, and click the DOWNLOAD ANDROID STUDIO button:

On the popup that appears, read and accept the terms and conditions and click the DOWNLOAD ANDROID STUDIO FOR MAC button: 

Note

The name of the button is different depending on the operating system you're using.

The download will begin and you'll be redirected to an instructions page (https://developer.android.com/studio/install).

Follow the instructions specified for your operating system to install Android Studio. When the installation is complete, open Android Studio and start the setup process. 

Getting Android Studio ready

On the Complete Installation screen, make sure theI do not have a previous version of Studio or I do not want to import my settings option is selected, and click the OK button:

On the Welcome screen, click Next to move to the Install Type screen:

Then, select the Standard option and click Next to continue:

On the Verify Settings screen, confirm your setup by clicking the Finish button:

The SDK components listed on the Verify Settings screen will start downloading. You can click on the Show Details button to view the details of the components being downloaded:

When the download and installation is complete, click the Finish button. That's it. You're done installing and setting up Android Studio.

Creating your first Android project

On the Welcome to Android Studio screen, click Start a new Android Studio project:

This starts the Create New Project wizard. On the Configure your new project screen, enter TicTacToe as the Application name. Specify the Company domain. The Package name is generated from the company domain and the application name. 

Set the Project location to a location of your choice, and click Next:

Choosing an SDK

On the Target Android Devices screen, you have to select the device types and the corresponding minimum version of Android required to run your app. The Android Software Development Kit (SDK) provides tools required to build your Android app irrespective of your language of choice.

Each new version of the SDK comes with a new set of features to help developers provide more awesome features in their apps. The difficulty, though, is Android runs on a very wide range of devices, some of which do not have the capabilities to support the latest versions of Android. This puts developers in a tough position of choosing between implementing great new features or supporting a wider range of devices. 

Android tries to make this decision easier by providing the following:

  • Data on the percentage of devices using specific SDKs to help developers make an informed choice. To view this data in Android Studio, click Help me choose under the minimum SDK dropdown. This will show you a list of currently supported Android SDK versions with their supported features, and the percentage of Android devices your app will support if you select that as your minimum SDK:

You can check out an up-to-date and more detailed version of that data on the Android developer dashboard (https://developer.android.com/about/dashboards/).

  • Android also provides support libraries to help with backward compatibility of certain new features added in newer SDK versions. Each support library is backward compatible to a specific API Level. Support libraries are usually named based on the API level with which they're backward compatible with. An example is appcompat-v7, which provides backward compatibility to API Level 7.

We'll discuss SDK versions further in a later section. For now, you can select API 15: Android 4.0.3 (IceCreamSandwich) and click Next:

The next screen is the Add an Activity to Mobile screen. This is where you select your default activity. Android Studio gives a number of options, from an activity with a blank screen to an activity with a login screen. For now, select the Basic Activity option and click Next:

On the next screen, enter the name and title of the activity, and the name of the activity layout. Then, click Finish:

Building your project

After clicking the Finish button, Android Studio generates and configures the project in the background for you. One of the background processes Android Studio performs is configuring Gradle. 

Gradle

Gradle is a build automation system that is easy to use, and can be used to automate the life cycle of your project, from building and testing to publishing. In Android, it takes your source code and configured Android build tools and generates an Android PackageKit (APK) file.

Android Studio generates the basic Gradle configurations needed to build your initial project. Let's take a look at those configurations. Open build.gradle:

The Android section specifies all Android-specific configurations, such as:

  • compileSdkVersion: Specifies the Android API level the app should be compiled with. 
  • buildToolsVersion: Specifies the build tool version your app should be built with.
  • applicationId: This is used to uniquely identify the application when publishing to the Play Store. As you may have noticed, it is currently the same as the package name you specified when creating the app. The applicationId defaults to the package name on creation, but that doesn't mean you can't make them different. You can. Just remember, you shouldn't change the applicationId again after you publish the first version of the app. The package name can be found in the app's Manifest file.

  • minSdkVersion: As specified earlier, this specifies the minimum API level required to run the app.

  • targetSdkVersion: Specifies the API level used to test your app.

  • versionCode: Specifies the version number of your app. This should be changed for every new version before publishing.

  • versionName: Specifies a user-friendly version name for your app.

The Dependencies section specifies dependencies needed to build your app.

Parts of an Android project

We will have a look at the different parts of our project. The screenshot depicts our project:

Let's take a further look at the different parts of our project:

  • The manifests/AndroidManifest.xml: Specifies important details about your app required by the Android system to run the app. Part of these details are:
    • The package name
    • Describing the components of the app, including the activities, services, and many more
    • Declaring the permissions required by your app
  • The res directory: Contains application resources such as images, xml layouts, colors, dimensions, and string resources:
    • The res/layout directory: Contains xml layouts that define the app's User Interface (UI)
    • The res/menu directory: Contains layouts that define the content of the app's menus
    • The res/values directory: Contains resources such as colors (res/values/colors.xml) and strings (res/values/strings.xml)
  • And, your Java and/or Kotlin source files

Running your app

Android gives you the ability to run your app on an actual device or a virtual one even before publishing it on the Google Play Store.

The Android emulator

The Android SDK comes with a virtual mobile device that runs on your computer and makes use of its resources. This virtual mobile device is called the emulator. The emulator is basically a configurable mobile device. You can configure its RAM size, screen size, and so on. You can also run more than one emulator. This is most helpful when you want to test your app on different device configurations (such as screen sizes and Android versions) but can't afford to get actual ones. 

Note

You can read more about the emulator on the developer page, at https://developer.android.com/studio/run/emulator. 

Creating an Android emulator

An Android emulator can be created from the Android Virtual Device (AVD) Manager. You can start the AVD Manager by clicking on its icon on the Android Studio toolbar, as shown in the following screenshot:

Or, alternatively, by selecting Tools | Android | AVD Manager from the menu:

On the Your Virtual Devices screen, click the Create Virtual Device... button:

Note

If you already have an emulator created, the button will be at the bottom of the screen:

The next step is to select the type of device you want to emulate. The AVD Manager allows you to create emulators for TVs, phones, tablets, and Android wear devices.

Make sure the Phone is selected in the Categorysection on the left-hand side of the screen. Go through the list of devices in the middle of the screen and choose one. Then, click Next:

On the System Image screen, select the version of Android you want your device to run on, and click Next:

Note

If the SDK version you want to emulate is not downloaded, click on the Download link next to it in order to download it.

On the Verify Configuration screen, go through and confirm the virtual device settings by clicking the Finish button:

You will be sent back to the Your Virtual Devices screen, with your new emulator showing the following:

You can click on the play icon under the Actions tab to start the emulator, or the pencil icon to edit its configurations.

Let's go ahead and start the emulator we just created by clicking on the play icon:

As you may have noticed, the virtual device comes with a toolbar on the right-hand side. That toolbar is known as the emulator toolbar. It gives you the ability to emulate functionalities such as shutdown, screen rotation, volume increase and decrease, and zoom controls.

Clicking on the More(...) icon at the bottom of the toolbar also gives you access to extra controls to simulate functionalities such as fingerprint, device location, message sending, phone calls, and battery power:

Running from an emulator

Running your app from an emulator is pretty easy. Click on the play icon on the Android Studio toolbar, as shown in the following screenshot:

On the Select Deployment Target screen that pops up, select the device you want to run the app on and click OK:

Android Studio will build and run your app on the emulator:

Note

If you do not already have an emulator running, your emulators will show up under the Available Virtual Devices section. Selecting them will start the emulator and then run your app on it:

Running on an actual device

To run your app on an actual device, you can build and copy the APK onto the device and run it from there. To do this, Android requires that the device is enabled to allow the installation of apps from unknown sources. To do this, perform the following steps:

  1. Open the Settings app on your device.
  2. Select Security.
  3. Look for and turn on the Unknown Sources option.

 

  1. You will be prompted about the danger that comes with installing apps from Unknown sources. Read carefully and click OK to confirm.
  2. That's it. You can now upload your APK and run it on the phone.

Note

You can easily disable the Unknown Sources setting by going back to Settings | Security and turning off the option.

We can all agree that this way of running your app is not very ideal, especially for debugging. With this in mind, Android devices come with the ability to run and debug your app very easily without having to upload your app to the device. This can either be done by connecting your device via a USB cable. To do this, Android requires Developer Mode to be enabled. Follow the instructions below to enable Developer Mode:

  1. Open the Settings app on your device.
  2. Scroll down and select About phone.
  3. On the Phone status screen, scroll down and tap Buildnumber multiple times until you see a toast that says You're now a developer!
  4. Go back to the Settings screen. You should now see a Developer options entry.
  5. Select Developer options.
  6. On the Developer options screen, turn on the switch at the top of the screen. If it's off, you'll be prompted with an Allow development settings? dialog. Click OK to confirm.
  7. Scroll down and turn on USB debugging. You'll be prompted with an Allow USB debugging? dialog. Click OK to confirm.
  8. Next, connect your device to your computer via the USB.
  9. You'll be prompted with another Allow USB debugging? dialog that has your computer's RSA key fingerprint. Check the Always allow from this computer option, and click OK to confirm.

You're now set to run your app on the device. Once again, click the Run button on the toolbar, select your device in the options shown in the Select Deployment Target dialog, and click OK:

That's it. You should now have your app showing on your device:

 

Summary


In this chapter, we went through the process of checking and installing the JDK, which is required for Android development. We also installed and set up our Android Studio environment. We created our first Android app and learned to run it on an emulator and on an actual device. 

In the next chapter, we'll learn to configure and set up Android Studio and our project for development with Kotlin.

About the Authors

  • Eunice Adutwumwaa Obugyei

    Eunice Obugyei is a software engineer from Accra, Ghana, with over 7 years of experience in Android development. Eunice is currently a senior software engineer at DreamOval Ltd, where she focuses on backend development and native mobile development. She is young, energetic, and always looking for an opportunity to learn and improve the skills in her arsenal. She is passionate about figuring out solutions to problems and finding the simplest way out, and her love for TV series and movies is her escape from the rigors of work life. Feel free to reach out on Twitter or LinkedIn.

    Browse publications by this author
  • Natarajan Raman

    Natarajan Raman has close to 15 years of experience in software design and development. He is a Google-certified Nano degree holder in Android development and was invited as a guest by Google for the I/O 2017. His Android App Idea for special children got selected as one of the top 6 ideas out of 80-odd ideas, and was also featured by Google in the Code it possible program. He works for Patterns and is also the managing trustee of Dream India.

    Browse publications by this author

Latest Reviews

(8 reviews total)
I explained already
Struggling hard to follow the book. First problem is that the version of Android Studio evolved in the meantime. The other problem is that the book tells about some changes you should do to the source files, but doesn't tell all. So you have to download the example files and compare with your version of the project to see what you're missing. The book is obviously written by a good Android developer, but its lacking to guide a beginner and anticipate the questions of the beginner. So its a steep learning curve with this book.
Clear instructions on how to setup Kotlin in the Android SDK followed by an introduction into programming in Kotlin and the syntax used.

Recommended For You

Book Title
Unlock this full book with a FREE 10-day trial
Start Free Trial