Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Mastering Android Development with Kotlin: Deep dive into the world of Android to create robust applications with Kotlin
Mastering Android Development with Kotlin: Deep dive into the world of Android to create robust applications with Kotlin
Mastering Android Development with Kotlin: Deep dive into the world of Android to create robust applications with Kotlin
Ebook591 pages1 hour

Mastering Android Development with Kotlin: Deep dive into the world of Android to create robust applications with Kotlin

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Kotlin is a programming language intended to be a better Java, and it's designed to be usable and readable across large teams with different levels of knowledge. As a language, it helps developers build amazing Android applications in an easy and effective way.

This book begins by giving you a strong grasp of Kotlin's features in the context of Android development and its APIs. Moving on, you'll take steps towards building stunning applications for Android. The book will show you how to set up the environment, and the difficulty level will grow steadily with the applications covered in the upcoming chapters.

Later on, the book will introduce you to the Android Studio IDE, which plays an integral role in Android development. We'll use Kotlin's basic programming concepts such as functions, lambdas, properties, object-oriented code, safety aspects, type parameterization, testing, and concurrency, which will guide you through writing Kotlin code in production. We'll also show you how to integrate Kotlin
into any existing Android project.

LanguageEnglish
Release dateNov 8, 2017
ISBN9781788474665
Mastering Android Development with Kotlin: Deep dive into the world of Android to create robust applications with Kotlin

Related to Mastering Android Development with Kotlin

Related ebooks

Programming For You

View More

Related articles

Reviews for Mastering Android Development with Kotlin

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Mastering Android Development with Kotlin - Miloš Vasić

    Mastering Android Development with Kotlin

    Mastering Android Development with Kotlin

    Deep dive into the world of Android to create robust applications with Kotlin

    Miloš Vasić

    BIRMINGHAM - MUMBAI

    Mastering Android Development with Kotlin

    Copyright © 2017 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: November 2017

    Production reference: 1061117

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham

    B3 2PB, UK.

    ISBN 978-1-78847-369-9

    www.packtpub.com

    Credits

    About the Author

    Miloš Vasić is a software engineer, author, and open source enthusiast. He holds a bachelor's degree in the programming of computer graphics and a master's degree in the field of Android programming; both degrees were gained at Singidunum University. He published his first book, Fundamental Kotlin, in October 2016, thus achieving his dream of becoming an author. He's currently employed at the Robert Bosch company, where he's working on SDKs for the auto-industry. When he is not working on new books, Miloš works on his open source projects.

    Acknowledgments

    This book has been a long and fun journey that I would not have manage to accomplish without help. So I think it's only polite to give gratitude.

    First of all, I would like to thank my girlfriend and personal assistant, Maja. She was the one who supported me and helped me while writing my first book Fundamental Kotlin and continued to do so with this one. She improved this book greatly by helping me write coherent text that is understandable even for those who are not experienced in programming.

    Next I would like to thank my editor at Packt Akshada. She was the best editor I could ask for and she helped me immensely with excellent advices and endless patience. The whole team at Packt that stands behind was book was incredibly supportive and helpful.

    Big thanks also to my friends who tolerated me and constantly filled me up with large amounts of coffee. Especially to my friend Vanja Petkovic. He was the technical editor for this book and it wouldn't be the same without him.

    And last but not least I would like to thank to my family for supporting me in my dream of becoming software engineer. They were with me and they were patient during all my phases! But, the most important of all, they believed in me!

    None of this would be possible if there weren't people who read my first book. I am forever grateful for their support. See you in my next book!

    Best wishes,

    Miloš

    About the Reviewer

    Vanja Petkovic studied math and computer science at Belgrade University, Serbia. There, he also obtained his MSc in computer science. He has been working as a software engineer for more than 13 years. Currently, he lives in Switzerland and works for Leica Geosystems in the 3D scanning department. He has specialized in software development for mobile devices and backend services. He started with software development for Palm OS, through Windows Mobile OS and Blackberry OS to Android OS and iOS today. His preferred weapons for developing backend services are Java and Spring.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Customer Feedback

    Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788473698.

    If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

    Table of Contents

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Downloading the color images of this book

    Errata

    Piracy

    Questions

    Starting with Android

    Why Kotlin?

    Kotlin for Android - it's official

    Downloading and configuring Android Studio

    Setting up Android emulators

    Creating a new AVD instance

    Duplicating an existing AVD and modifying it by need

    Android Debug Bridge

    Other important tools

    Initializing a Git repository

    Creating an Android project

    Setting up Gradle

    Explaining directory structure

    Defining build types and flavors

    Additional libraries

    Getting familiar with Android Manifest

    Main Application class

    Your first screen

    Summary

    Building and Running

    Running your first Android application

    Meet the Logcat

    First case

    Using the Gradle build tool

    Debug your application

    Summary

    Screens

    Analyzing the mockup plan

    Defining application activities

    Android layouts

    Using EditText views

    The margins attribute

    The padding attribute

    Checking out the gravity attribute

    Looking at other attributes

    Understanding Android Context

    Understanding fragments

    Fragment manager

    Fragments stack

    Creating View Pager

    Making animations with transitions

    Dialog fragments

    Notifications

    Other important UI components

    Summary

    Connecting Screen Flow

    Creating an application bar

    Using the navigation drawer

    Connecting activities

    Looking deeper into Android Intents

    Passing information between activities and fragments

    Summary

    Look and Feel

    Themes in the Android Framework

    Styles in Android

    Working with assets

    Using custom fonts

    Applying coloring

    Make your buttons look pretty

    Setting animations

    Animation sets in Android

    Summary

    Permissions

    Permissions from Android Manifest

    Requesting permissions

    Doing it the Kotlin way

    Summary

    Working with Databases

    Introduction to SQLite

    Benefits

    Describing our database

    CRUD operations

    Insert CRUD operation

    Update CRUD operation

    Delete CRUD operation

    Select CRUD operation

    Tying things together

    Summary

    Android Preferences

    What are Android preferences?

    How can you use them?

    Editing (storing) preferences

    Removing preferences

    Defining your own preferences manager

    Summary

    Concurrency in Android

    Introduction to Android concurrency

    Main thread

    Handlers and threads

    AsyncTask

    Understanding Android Looper

    Preparing the Looper

    Delayed execution

    Summary

    Android Services

    Service categorization

    Foreground Android services

    Background Android services

    Bound Android services

    Android service basics

    Declaring your service

    Starting the service

    Stopping the service

    Binding to Android service

    Stopping the service

    Service lifecycle

    Defining the main application service

    Defining the intent service

    Summary

    Messaging

    Understanding Android broadcasts

    System broadcasts

    Listening for broadcasts

    Registering from the context

    Receivers execution

    Sending broadcasts

    Creating your own broadcast messages

    Using on boot and on shutdown broadcasts

    Listening for network events

    Summary

    Backend and API

    Identifying entities used

    Working with data classes

    Connect data models to a database

    Introduction to Retrofit

    Defining Retrofit service

    Building a Retrofit service instance

    Introduction to Gson with Kotson library

    What else is available?

    Retrofit alternative

    Gson alternative

    Executing our first API call

    Content providers

    Android adapters

    Content loaders

    Data binding

    Using lists

    Using grids

    Implementing drag and drop

    Summary

    Tuning Up for High Performance

    Optimizing layouts

    Optimizing battery life

    Keeping your application responsive

    Summary

    Testing

    Adding dependencies

    Updating folder structure

    Writing your first test

    Using test suites

    How to test UI

    Running tests

    Running unit tests

    Running instrumentation tests

    Summary

    Migration to Kotlin

    Preparing the migration

    Danger signs

    Updating dependencies

    Converting classes

    Refactoring and cleanup

    Summary

    Deploying Your Application

    Preparing for deployment

    Code obfuscation

    Signing your application

    Publishing to Google Play

    Summary

    Preface

    Android is the most popular platform for mobile devices. Every year, there are more and more developers getting involved in Android development. The Android Framework makes it possible to develop applications for mobile phones, tablets, televisions, and much more! So far, all development has been done in Java. Recently, Google announced Kotlin as the second language developers can use. Because of this, and with Kotlin's ever-growing popularity, we decided to introduce you to Android using Kotlin as its primary development programming language.

    With Kotlin, you can do everything you can do with Java, but with more joy and fun! We will show you how to play with Android and Kotlin, and how to create amazing things! Thanks to Kotlin, it's certain that the Android platform will evolve even more. In the near future, it's not impossible that Kotlin will become the primary development language for the platform. Take your seat and get ready for a great journey!

    What this book covers

    Chapter 1, Starting with Android, teaches you how to start Android development with Kotlin and how to set up your working environment.

    Chapter 2, Building and Running, shows you how to build and run your project. It will demonstrate how to log and debug the application.

    Chapter 3, Screens, starts with the UI. In this chapter, we will create the first screens for our application.

    Chapter 4, Connecting Screen Flow, explains how to connect the screen flow and define basic user interaction with the UI.

    Chapter 5, Look and Feel, covers the theming of the UI. We will introduce you to the basic concepts of theming in Android.

    Chapter 6, Permissions, explains that in order to take advantage of certain system functionalities, it's necessary to get proper system permissions, which are discussed in this chapter.

    Chapter 7, Working with Databases, shows you how to use SQLite as storage for your application. You will create a database to store and share data.

    Chapter 8, Android Preferences, states that not all data should be stored in the database; some information can be stored in shared preferences. We will explain why and how.

    Chapter 9, Concurrency in Android, explains that if you are familiar with concurrency in programming, then you will know that, in software, many things happen simultaneously. Android is not an exception!

    Chapter 10, Android Services, presents Android services and how to use them.

    Chapter 11, Messaging, says that in Android, your application can listen for various events. How to do this will be answered in this chapter.

    Chapter 12, Backend and API, connects to the remote backend instance to obtain the data.

    Chapter 13, Tuning Up for High Performance, is the perfect chapter to give you answers when you are not sure if your application is fast enough.

    Chapter 14, Testing, mentions that before we release anything, we must test it. Here, we will explain how to write tests for your application.

    Chapter 15, Migration to Kotlin, guides you if you plan to migrate the existing Java code base into Kotlin.

    Chapter 16, Deploying Your Application, guides you through the deployment process. We will release everything we develop during this book.

    What you need for this book

    For this book, a modern computer running Microsoft Windows, Linux, or macOS is required. You will need Java JDK, the Git version-control system, and Android Studio installed.

    To run all code examples and the code you write, you will need an Android phone running Android with OS version >= 5.

    Who this book is for

    The book is aimed at developers who want to build amazing Android applications in an easy and effective way. Basic knowledge of Kotlin is assumed, having no familiarity with Android development.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, and user input are shown as follows: We will add proper log messages for each lifecycle event of the Application class and the screen (activity) we created.

    A block of code is set as follows:

        override fun onCreate(savedInstanceState: Bundle?) {

          super.onCreate(savedInstanceState)

          setContentView(R.layout.activity_main)

          Log.v(tag, [ ON CREATE 1 ])

        }

    Any command-line input or output is written as follows. The input command might be broken into several lines to aid readability, but needs to be entered as one continuous line in the prompt:

    sudo apt-get install libc6:i386 libncurse

    libstdc++6:i386 lib32z1 libbz2-1.0:i386

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: " Select Tools | Android | AVDManager or click on the AVDManager icon in the toolbar."

    Warnings or important notes appear like this.

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on theSUPPORTtab at the top.

    Click onCode Downloads & Errata.

    Enter the name of the book in theSearchbox.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click onCode Download.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/-Mastering-Android-Development-with-Kotlin/branches/all. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Downloading the color images of this book

    We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringAndroidDevelopmentwithKotlin_ColorImages.pdf.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--maybe a mistake in the text or the code--we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at [email protected] with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

    Starting with Android

    Kotlin has been officially announced by Google as a first-class programming language for Android. Find out why Kotlin is the best tool available for you as a newcomer and why senior Android developers first adopted Kotlin.

    In this chapter, you will learn how to set up a working environment. You will install and run Android Studio and set up Android SDK and Kotlin. Here, you will also be introduced to some important and useful tools such as Android Debug Bridge (adb).

    Since you don't have your project yet, you will set it up. You will initialize a Git repository to track changes in your code and create an empty project. You will enable it to support Kotlin and add support for additional libraries that we will use.

    After we have initialized the repository and project, we will go through the project structure and explain each file the IDE has generated. Finally, you will create your first screen and take a look at it.

    This chapter will cover the following points:

    Setting up an environment for the development of Git and Gradle basics

    Working with Android Manifest

    Android emulator

    Android tools

    Why Kotlin?

    Before we start our journey, we will answer the question from the chapter title--Why Kotlin? Kotlin is a new programming language developed by JetBrains, the company that developed IntelliJ IDEA. Kotlin is concise and understandable, and it compiles everything to bytecode just like Java. It can also compile to JavaScript or native!

    Kotlin comes from professionals of the industry and solves problems programmers are facing every day. It is easy to start and adopt! IntelliJ comes with a Java to Kotlin converter tool. You can convert Java code file by file and everything will still work flawlessly.

    It is interoperable and can use any existing Java Framework or library. The interoperability is impeccable and does not require wrappers or adapter layers. Kotlin supports build systems such as Gradle, Maven, Kobalt, Ant, and Griffon with external support.

    The most important thing about Kotlin, for us, is that it works perfectly with Android.

    Some of the most impressive Kotlin features are as follows:

    Null safety

    Exceptions are unchecked

    Type inference works everywhere

    One-liner functions take one line

    Generated getters and setter out of the box

    We can define functions outside of classes

    Data classes

    Functional programming support

    Extension functions

    Kotlin uses Markdown instead of HTML for API documents! The Dokka tool, a Javadoc alternative, can read Kotlin and Java source code and generate combined docs

    Kotlin has a better generics support than Java

    Reliable and performant concurrent programming

    String patterns

    Named method arguments

    Kotlin for Android - it's official

    On May 17th 2017, Google announced that it's making Kotlin, a statically typed programming language for the Java Virtual Machine, a first-class language to write Android apps.

    The next version of Android Studio (3.0, current one is 2.3.3) will support Kotlin out of the box. Google will put its effort in the future of Kotlin.

    It is important to note that this is only an additional language, not a replacement for existing Java and C++ support (for now).

    Downloading and configuring Android Studio

    To develop our application, we will need some tools. First of all, we will need an IDE. For that purpose, we will use Android Studio. Android Studio provides the fastest tools to build apps on every type of Android device.

    Android Studio offers professional code editing, debugging, and performance tooling. It's a flexible build system that allows you to focus on building a top quality application.

    Setting up Android Studio takes just a few clicks. Before we go any further, you need to download the following version for your operating system:

    https://developer.android.com/studio/index.html

    Here are the instructions for macOS, Linux, and Windows:

    macOS:

    To install it on macOS, follow these steps:

    Launch the Android Studio DMG file.

    Drag and drop Android Studio into the Applications folder.

    Launch Android Studio.

    Select whether you want to import previous Android Studio settings.

    Click on OK.

    Follow the instructions until Android Studio is ready for use.

    Linux:

    To install it on Linux, follow these steps:

    Unpack the archive you downloaded to an appropriate location for your applications.

    Navigate to bin/directory/.

    Execute/studio.sh.

    Select whether you want to import previous Android Studio settings or not.

    Click on OK.

    Follow the instructions until Android Studio is ready for use.

    Optionally, select Tools | Create Desktop Entry from the menu bar.

    If you are running a 64-bit version of Ubuntu, you need to install some 32-bit libraries with the following command:

    sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386

    In case you are running a 64-bit Fedora, the command is follows:

    sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686

    Windows:

    To install it on Windows, follow these steps:

    Execute the .exe file you downloaded.

    Follow the instructions until Android Studio is ready for use.

    Setting up Android emulators

    Android SDK comes with emulators capable of running applications we develop. We will need it for our project! The purpose of an emulator is to simulate a device and displays all its activity windowed on your computer. What can we do with it? We can prototype, develop, and test--all this without a hardware device. You can emulate phones, tablets, wearables, and TV devices. You can create your own device definitions, or you can use predefined emulators.

    The good thing about emulators is that they are fast. In many situations, it will take less time to run an application on an emulator instance than on a real hardware device.

    Working with the emulators is just as easy with a real hardware device. For gestures, you use your mouse, and for input, your keyboard.

    Emulators can do anything a real phone does! You can easily send incoming phone calls and text messages! You can specify the location of the device, send fingerprint scans, adjust network speed and status, or even simulate battery properties. Emulators can have a virtual SD card and internal data storage, both of them you can use to send real files to that space.

    Android Virtual Device (AVD) configuration is used to define an emulator. Each AVD instance works as a completely independent device! For the purpose of creating and management of AVDs, we use the AVD Manager. An AVD definition holds a hardware profile, system image, storage area, skin, and other important properties.

    Let's play with it! To run the AVD Manager, do one of the following:

    Select Tools | Android | AVDManager or click on the AVDManager icon in the toolbar:

    It displays all AVDs you've already defined. As you can see, we don't have any yet!

    What

    Enjoying the preview?
    Page 1 of 1