© Peter Späth 2019
Peter SpäthLearn Kotlin for Android Developmenthttps://doi.org/10.1007/978-1-4842-4467-8_1

1. Your First Kotlin Application: Hello Kotlin

Peter Späth1 
(1)
Leipzig, Germany
 

In this chapter we are going to learn how to use the Android Studio integrated development environment (IDE) to write and execute a first simple Kotlin program.

Setting Up an IDE: Android Studio

Although computer programs could be written in simple text editors and then prepared and executed by some system-level commands entered in a system terminal, using an IDE helps in keeping project files together and also simplifies various development-related activities.

Note

Computer languages come in two flavors: Either you have some program code that by some execution engine gets interpreted while the program is running and then executed on the CPU, or you have a compiling language with a special preparatory system command first translating the program code into a compiled program that can be directly executed by the operating system or by some specially tailored execution engine. Kotlin is such a compiling language. If you use an IDE like Android Studio, the compilation step usually is automatically done for you.

In this book we use Android Studio as an IDE. It is developed by Google, Inc., and based on the community edition of the IntelliJ IDEA. You can freely download, install, and use it. As of this writing, the download page is hosted at https://developer.android.com/studio/ . If that link is not functioning, you can easily find the download location by entering “android studio download” in your favorite search engine. To use Android Studio, you don’t have to buy a license for private or commercial projects. To install Android Studio on your PC, follow these steps:
  1. 1.

    Download the installer for your operating system. There are installers for Linux (tested for Ubuntu 14.04; higher versions should work as well), Windows (starting from version 7), and MacOS (starting from MacOS X 10.10).

     
  2. 2.

    Start the installer. For Linux, unpack the installer ZIP, then navigate to the bin folder and start studio.sh in a terminal. On Windows systems, start the .exe file. On MacOS X systems, launch the .dmg file and then drag and drop Android Studio to the Applications folder. Launch it again from there.

     

Note

To open a terminal in Ubuntu Linux press Ctrl+Alt+T. Inside the terminal, commands need to be entered using the keyboard. To change to a directory enter cd /path/to/directory. To start a .sh file enter ./name.sh

The details of the installation depend on your operating system specifics, including the operating system version, and also the version of your Android Studio download. The page where you downloaded Android Studio will give you more details and even present videos for the installation procedure.

In any case the installer for Android Studio will download additional components. The same holds for the Project Wizard when you create new projects, depending on the features needed for the project and also depending on the components already installed. You thus need to have some patience before you can start your first project; subsequent startups will, of course, be faster.

Proceed with the installer up to the point where you are being asked whether you want to create a new project. For Linux this will look like Figure 1-1, and for other operating systems you will be presented something similar.
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig1_HTML.jpg
Figure 1-1

The Project Creation Wizard

Connecting Your Android Device

First it is important to say that for developing Android apps you don’t necessarily need to have a real hardware device at hand. In the section “Setting Up and Using Emulators” later in this chapter, we talk about how to use emulators to simulate Android devices. For professional apps, however, it is a good idea to have at least one Android hardware device at hand.

Android Studio allows for working with both real and simulated devices. To work with only a real device like a smartphone obviously can give you the most profound assurance your app is running. However, it will tell you only your smartphone can operate your app; you cannot be sure other devices will be just as happy with it. You certainly don’t want to buy dozens of different smartphones and other Android devices. Likewise, though, working only with simulated devices and not with a real device cannot give you 100 percent assurance your app works on any real devices.

The suggested development technique therefore is to use both real and simulated devices. You don’t have to check each and every development step in both worlds, but once you reach a milestone you should do a double check. Of course, before you publish your app and make it available to a broader audience, you should test it on both real and simulated devices.

Your process to connect the studio to a real device might vary, but ideally all you have to do is connect your smartphone to the USB port of your PC or laptop and make sure your device is a debuggable device. Describing solutions for any problem that might come up doesn’t make too much sense here, because any update of your operating system or Android Studio can easily change the picture. Therefore if you have problems, please consult the official Android and Android Studio documentation, and use your favorite search engine to find corresponding blog entries. The procedure for connecting hardware devices basically goes as follows:
  1. 1.

    To make your smartphone debuggable, for Android version 4.2 or higher, open the Settings dialog box, go to About phone, and tap seven times on the build number. For versions prior to that, you might instead have to go to Settings ➤ Develop Option ➤ Check “USB debugging.”

     
  2. 2.

    Connect the smartphone to your laptop or PC via USB cable.

     
To see whether the studio actually got connected to the device, go to Tools ➤ Android ➤ Android Device Monitor. You should see your device listed in the devices section of the Device Monitor, as shown in Figure 1-2.
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig2_HTML.jpg
Figure 1-2

A hardware Android device

Starting Your First Kotlin App

It is now time to write our first Kotlin application inside Android Studio. From the installation step where you are being asked whether you want to create a project, or after you start an installed Android Studio instance the first time, or from inside a running Android Studio at File ➤ New ➤ New Project, inside the menu, proceed as follows:
  1. 1.

    Select or click Start a New Android Studio Project.

     
  2. 2.

    Inside the Project Wizard, as the application name, enter HelloKotlin. Although not strictly necessary, it is better to avoid space characters inside the name.

     
  3. 3.

    For company domain, enter example.com. Aside from not using spaces, what you enter here is up to you. It is, however, good practice to enter a real domain name you or your company owns. For projects you know you will never publish, choose whatever you like.

     
  4. 4.

    The project location that Android Studio suggests is decent enough, but if you like you can choose a different one.

     
  5. 5.

    Make sure Include Kotlin support is selected.

     
  6. 6.

    Choose Phone and Tablet as a form factor.

     
  7. 7.

    Choose API 19 as a minimum software development kit (SDK).

     
  8. 8.

    Choose Empty Activity. As Activity name, use the suggested MainActivity. Make sure Generate Layout File is selected, and as a layout name, accept the suggested activity_main. Make sure Backwards Compatibility is selected as well.

     

The first time you create a project Android Studio will automatically download and install any additional components it needs, and then it also performs an initial build. This will take several minutes, so be patient here.

At this point if everything worked well the Android Studio main window will appear as shown in Figure 1-3.
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig3_HTML.jpg
Figure 1-3

The Android Studio main window

Setting Up and Using Emulators

Now it is time to install a device emulator. Emulators are very handy, because they allow for developing Android apps without having to connect a real device. Emulators simulate Android devices on your computer’s screen. To install one of the several available, go to Tools ➤ AVD Manager. The screen that appears shows the title Your Virtual Devices. Click Create Virtual Device. The following screen shows a device list, as shown in Figure 1-4.
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig4_HTML.jpg
Figure 1-4

Emulated devices

Under Category, make sure you select Phone. In the middle pane, select the Nexus 6 entry. Click Next. On the next screen, click the Download link for Oreo, API 27. Go through the subwizard that then appears. Here a system image gets downloaded; this is something like the operating system for the emulator device. Back on the System Image screen, the Oreo, API 27 item now gets selected and it is possible to click Next. Click Next, and on the next screen click Finish.

The Your Virtual Devices screen now shows one entry, as displayed in Figure 1-5. You can now close that window.
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig5_HTML.jpg
Figure 1-5

Emulated devices with an entry

Continuing with the HelloKotlin App

Back in the Android Studio main window, on the left side inside the app, by clicking on the small triangles next to the names you can navigate to the following files (see Figure 1-6):
app →  java →
    com.example.hellokotlin → MainActivity
app →  res →
    layout →  activity_main.xml
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig6_HTML.jpg
Figure 1-6

The HelloKotlin app

Double-clicking on any of the files will display them in the editor in the center pane of the window. The two files MainActivity and activity_main.xml are the central files we will need to adjust for our first simple Kotlin app. The file activity_main.xml defines the layout on the smartphone’s screen. We will adapt it to show a button and a text area. For that purpose, open the file, switch to the text view of the editor by selecting the Text tab on the bottom of the pane, and then as its contents, write the following:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android=
          "http://schemas.android.com/apk/res/android"
        xmlns:tools=
          "http://schemas.android.com/tools"
        xmlns:app=
          "http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">
      <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Go"
                android:onClick="go"/>
      <EditText
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="textMultiLine"
                android:ems="10"
                tools:layout_editor_absoluteY="286dp"
                tools:layout_editor_absoluteX="84dp"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

So much for the graphical design. The program goes into the MainActivity.kt file . Open this one in the editor by double-clicking the name.

As its contents, write the following:
package kotlin.hello.hellokotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
  }
  fun go(v:View) {
      text.setText("Hello Kotlin!" + " " + Date())
  }
}

Start the app by clicking the green triangle in the task button bar on top of the window. From the Available Virtual Devices list, choose Nexus 6 API 27, then click OK. The first time you might be asked whether you want to install a feature called Instant Run. If so, click Install and Continue.

Now the emulator window appears. The app gets built, sent to the emulator, and started there, as shown in Figure 1-7.
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig7_HTML.jpg
Figure 1-7

HelloKotlin app started

Click Go and the emulated devices screen gets updated to show the text “Hello Kotlin!” and the current date, as shown in Figure 1-8.
../images/476388_1_En_1_Chapter/476388_1_En_1_Fig8_HTML.jpg
Figure 1-8

HelloKotlin app on the device

Congratulations! You just wrote, compiled, and ran your first Kotlin application!

Using the Command Line

Although you can continue using Android Studio for working on projects to any depth, it is also possible to use the command line in a terminal to build and run apps. If you want to continue using Android Studio, you can safely skip this section. For all others, I want to describe how to use a terminal to build apps, and more precisely the HelloKotlin app we created in the last section.

Note

Using the command line helps, for example, in cases where you don’t have a desktop environment, like on servers. You can also use it in an automated build environment where developers provide the code, but the program to be executed on Android devices is generated automatically.

Interestingly, Android Studio helps us to get rid of itself. For any project you have successfully built inside Android Studio, the folder containing the project files also will contain specially tailored build scripts that you can use to build apps without using Android Studio.

First we need to open a terminal: In Ubuntu Linux, press Ctrl+Alt+T. In Windows you find a terminal by searching for CMD in the system menu. For Apple Mac OS, a terminal can be opened after you search for Terminal in Spotlight. Next we need to know where in the file system the project files reside. If you accepted the suggestion Android Studio gave while creating the project, the paths will be as follows:
/home/[USER]/AndroidStudioProjects/HelloKotlin
    for Linux
/Users/[USER]/AndroidStudioProjects/HelloKotlin
    for Mac OS X
C:Users[USER]AndroidStudioProjectsHelloKotlin
    for Windows

where [USER] is your logon username. If you used a custom project location instead, you have to use that one.

Fluently using a terminal is an art and we won’t go into details here. The following commands will, however, give you a starting point. Inside the terminal we change to the project folder as follows:
cd [PATH]        #for Linux and Mac OS X and Windows
where [PATH] is the project folder we just determined. From here we can build the app by entering
./gradlew app:build      #for Linux and Mac OS X
gradlew   app:build      #for Windows

Note

The gradlew command belongs to the Gradle build system. Gradle gets used throughout Android Studio for building executable apps.

The final app as an APK file with an .apk suffix will now show up inside app/build/outputs/apk/debug/. The APK comes from Android PacKage; such a file is a compressed collection of all the files Android needs to install an app on your device. The gradlew wrapper script actually allows for many more options to build and investigate projects. Enter -help or tasks as an argument to have them all listed.
./gradlew –help    #for Linux and Mac OS X
./gradlew tasks    #for Linux and Mac OS X
gradlew –help      #for Windows
gradlew tasks      #for Windows

For the tasks command to specifically show the app’s tasks, you have to prepend app:, which we saw earlier for the build task.

Note

Describing what you can do with such an APK file resulting from a build is left to an Android book. As a hint to get you started, learn how to use the tools provided in the SDK, especially the adb platform tool.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.130.13