Android Programming with Kotlin for Beginners - John Horton - E-Book

Android Programming with Kotlin for Beginners E-Book

John Horton

0,0
33,77 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build smart looking Kotlin apps with UI and functionality for the Android platform

Key Features



  • Start your Android programming career, or just have fun publishing apps on Google Play marketplace
  • The first-principle introduction to Kotlin through Android, to start building easy-to-use apps
  • Learn by example and build four real-world apps and dozens of mini-apps

Book Description



Android is the most popular mobile operating system in the world and Kotlin has been declared by Google as a first-class programming language to build Android apps. With the imminent arrival of the most anticipated Android update, Android 10 (Q), this book gets you started building apps compatible with the latest version of Android.



It adopts a project-style approach, where we focus on teaching the fundamentals of Android app development and the essentials of Kotlin by building three real-world apps and more than a dozen mini-apps. The book begins by giving you a strong grasp of how Kotlin and Android work together before gradually moving onto exploring the various Android APIs for building stunning apps for Android with ease. You will learn to make your apps more presentable using different layouts. You will dive deep into Kotlin programming concepts such as variables, functions, data structures, Object-Oriented code, and how to connect your Kotlin code to the UI. You will learn to add multilingual text so that your app is accessible to millions of more potential users. You will learn how animation, graphics, and sound effects work and are implemented in your Android app.



By the end of the book, you will have sound knowledge about significant Kotlin programming concepts and start building your own fully featured Android apps.

What you will learn



  • Learn how Kotlin and Android work together
  • Build a graphical drawing app using Object-Oriented Programming (OOP) principles
  • Build beautiful, practical layouts using ScrollView, RecyclerView, NavigationView, ViewPager and CardView
  • Write Kotlin code to manage an apps' data using different strategies including JSON and the built-in Android SQLite database
  • Add user interaction, data captures, sound, and animation to your apps
  • Implement dialog boxes to capture input from the user
  • Build a simple database app that sorts and stores the user's data

Who this book is for



This book is for people who are new to Kotlin, Android and want to develop Android apps.It also acts as a refresher for those who have some experience in programming with Android and Kotlin.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 793

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Android Programming with Kotlin for Beginners
Why subscribe?
Packt.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
1. Getting Started with Android and Kotlin
Why use Kotlin and Android?
The beginner's first stumbling block
How Kotlin and Android work together
The Android API
Kotlin is object-oriented
Run that by me again – what, exactly, is Android?
Android Studio
Setting up Android Studio
Final step – for now
What makes an Android app?
Android resources
The structure of Android's code
Packages
Classes
Functions
Our first Android app
Possible extra step 1
Possible extra step 2
Deploying the app so far
Running and debugging the app on an Android emulator
Running the app on a real device
Frequently asked question
Summary
2. Kotlin, XML, and the UI Designer
Examining the log output
Filtering the logcat output
Exploring the project's Kotlin code and the main layout's XML code
Examining the MainActivity.kt file
Code folding (hiding) in Android Studio
The package declaration
Importing classes
The class declaration
Functions inside the class
A summary of the Kotlin code so far
Examining the main layout file
UI layout elements
UI text elements
Adding buttons to the main layout file
Adding a button via the visual designer
Editing the button's attributes
Examining the XML code for the new button
Adding a button by editing the XML code
Giving the buttons unique id attributes
Positioning the two buttons in the layout
Making the buttons call different functions
Leaving comments in our Kotlin code
Coding messages to the user and the developer
Writing our first Kotlin code
Adding message code to the onCreate function
Examining the output
Writing our own Kotlin functions
Examining the output
Frequently asked questions
Summary
3. Exploring Android Studio and the Project Structure
A quick guided tour of Android Studio
Project Explorer and project anatomy
The Empty Activity project
Exploring the Empty Activity project
The manifests folder
The java folder
The res folder
The res/drawable folder
The res/layout folder
The res/mipmap folder
The res/values folder
The colors.xml file
The strings.xml file
The styles.xml file
The Basic Activity project
Exploring the Basic Activity project
The MainActivity.kt file
The activity_main.xml file
The extra functions in MainActivity.kt
The content_main.xml file
Exploring the Android emulator
The emulator control panel
Using the emulator as a real device
Accessing the app drawer
Viewing active apps and switching between apps
Summary
4. Getting Started with Layouts and Material Design
Material design
Exploring Android UI design
Layouts
Creating the Exploring Layouts project
Building a menu with LinearLayout
Adding a LinearLayout to the project
Preparing your workspace
Examining the generated XML
Adding a TextView to the UI
Adding a multi-line TextView to the UI
Wiring up the UI with the Kotlin code (part 1)
Adding layouts within layouts
Making the layout look pretty
Wiring up the UI with the Kotlin code (part 2)
Building a precise UI with ConstraintLayout
Adding a CalenderView
Resizing a view in a ConstraintLayout
Using the Component Tree window
Adding constraints manually
Adding and constraining more UI elements
Making the text clickable
Laying out data with TableLayout
Adding a TableRow to TableLayout
Using the Component Tree when the visual designer won't do
Organizing the table columns
Linking back to the main menu
Summary
5. Beautiful Layouts with CardView and ScrollView
Attributes – a quick summary
Sizing using dp
Sizing fonts using sp
Determining size with wrap or match
Using padding and margin
Using the layout_weight property
Using gravity
Building a UI with CardView and ScrollView
Setting the view with Kotlin code
Adding image resources
Creating the content for the cards
Defining dimensions for CardView
Adding CardView to our layout
Including layout files inside another layout
Themes and material design
Using the Android Studio theme designer
Creating a tablet emulator
Frequently asked question
Summary
6. The Android Lifecycle
The life and times of an Android app
How Android interacts with our apps
A simplified explanation of the Android lifecycle
The lifecycle phases demystified
How we handle the lifecycle phases
The lifecycle demo app
Coding the lifecycle demo app
Running the lifecycle demo app
Examining the lifecycle demo app output
Some other overridden functions
The structure of Kotlin code – revisited
Summary
7. Kotlin Variables, Operators, and Expressions
Learning the jargon
More on code comments
Variables
Types of variables
Declaring and initializing variables
Saving keystrokes with type inference
Operators and expressions
The assignment operator
The addition operator
The subtraction operator
The division operator
The multiplication operator
The increment operator
The decrement operator
The express yourself demo app
Summary
8. Kotlin Decisions and Loops
Making decisions in Kotlin
Indenting code for clarity
More Kotlin operators
The comparison operator
The logical NOT operator
The NOT equal operator
The greater-than operator
The less-than operator
The greater-than-or-equal-to operator
The less-than-or-equal-to operator
The logical AND operator
The logical OR operator
How to use all these operators to test variables
Using the if expression
If they come over the bridge, shoot them!
Else do this instead
Using when to make decisions
The When Demo app
Repeating code with loops
while loops
do-while loops
Ranges
For loops
Controlling loops with break and continue
Sample code
Summary
9. Kotlin Functions
Function basics and recap
The basic function declaration
Function parameter lists
The return type and the return keyword
Function bodies and single-expression functions
Making functions flexible
Default and named arguments
Even more on functions
Summary
10. Object-Oriented Programming
Introducing OOP
What is OOP exactly?
Encapsulation
Polymorphism
Inheritance
Why do it like this?
Class recap
Basic classes
Declaring a class
Instantiating a class
Classes have functions and variables (kind of)
Using the variables of a class
Using the functions and variables of a class
Class variables are properties
Examples using properties with their getters, setters, and fields
When to use overridden getters and setters
Visibility modifiers
Public
Private
Protected
Internal
Visibility modifiers summary
Constructors
Primary constructors
Secondary constructors
We need to talk about this
Using the Meeting class
Init blocks
Basic classes app and using the init block
Introduction to references
Summary
11. Inheritance in Kotlin
OOP and inheritance
Using inheritance with open classes
Basic inheritance examples
Overriding functions
Summary so far
More polymorphism
Abstract classes and functions
Classes using the Inheritance example app
Summary
12. Connecting Our Kotlin to the UI and Nullability
All the Android UI elements are classes too
A quick break to throw out the trash
Seven useful facts about the Stack and the Heap
So, how does this Heap thing help me?
Kotlin interfaces
Using buttons and TextView widgets from our layout with a little help from interfaces
Nullability – val and var revisited
Null objects
Safe call operator
Non null assertion
Nullability in review
Summary
13. Bringing Android Widgets to Life
Declaring and initializing the objects from the layout
Creating UI widgets from pure Kotlin without XML
Exploring the palette – part 1
The EditText widget
The ImageView widget
RadioButtons and RadioGroups
Lambdas
Writing the code for the overridden function
Exploring the palette – part 2, and more lambdas
The Switch widget
The CheckBox widget
The TextClock widget
The widget exploration app
Setting up the widget exploration project and UI
Coding the widget exploration app
Coding the CheckBox widget
Changing transparency
Changing color
Changing size
Coding the RadioButton widgets
Using a lambda for handling clicks on a regular Button widget
Coding the Switch widget
Running the Widget Exploration app
Converting layouts to ConstraintLayout
Summary
14. Android Dialog Windows
Dialog windows
Creating the dialog demo project
Coding a DialogFragment class
Using chaining to configure the DialogFragment class
Using the DialogFragment class
The Note to self app
Using String resources
How to get the code files for the Note to self app
The completed app
Building the project
Preparing the String resources
Coding the Note class
Implementing the dialog designs
Coding the dialog boxes
Coding the DialogNewNote class
Coding the DialogShowNote class
Showing and using our new dialogs
Coding the floating action button
Summary
15. Handling Data and Generating Random Numbers
A random diversion
Handling large amounts of data with arrays
Arrays are objects
A simple mini-app array example
Getting dynamic with arrays
A dynamic array example
ArrayLists
Arrays and ArrayLists are polymorphic
Hashmaps
The Note to self app
Frequently asked questions
Summary
16. Adapters and Recyclers
Inner classes
RecyclerView and RecyclerAdapter
The problem with displaying lots of widgets
The solution to the problem with displaying lots of widgets
How to use RecyclerView and RecyclerAdapter
What we will do to set up RecyclerView with RecyclerAdapter and an ArrayList of notes
Adding RecyclerView, RecyclerAdapter, and ArrayList to the Note to Self project
Removing the temporary "Show Note" button and adding RecyclerView
Creating a list item for RecyclerView
Coding the RecyclerAdapter class
Coding the onCreateViewHolder function
Coding the onBindViewHolder function
Coding getItemCount
Coding the ListItemHolder inner class
Coding MainActivity to use the RecyclerView and RecyclerAdapter classes
Adding code to onCreate
Modifying the createNewNote function
Coding the showNote function
Running the app
Frequently asked questions
Summary
17. Data Persistence and Sharing
The Android Intent class
Switching Activity
Passing data between Activities
Adding a settings page to Note to self
Creating the SettingsActivity
Designing the settings screen layout
Enabling the user to switch to the "Settings" screen
Persisting data with SharedPreferences
Reloading data with SharedPreferences
Making the Note to self settings persist
Coding the SettingsActivity class
Coding the MainActivity class
More advanced persistence
What is JSON?
Exceptions – try, catch, and finally
Backing up user data in Note to self
Frequently asked questions
Summary
18. Localization
Making the Note to self app Spanish, English, and German
Adding Spanish support
Adding German support
Adding the String resources
Running Note to self in German or Spanish
Making the translations work in Kotlin code
Summary
19. Animations and Interpolations
Animations in Android
Designing cool animations in XML
Fading in and out
Move it, move it
Scaling or stretching
Controlling the duration
Rotate animations
Repeating animations
Combining an animation's properties with sets
Instantiating animations and controlling them with Kotlin code
More animation features
Listeners
Animation interpolators
Animations demo app – introducing SeekBar
Laying out the animation demo
Coding the XML animations
Wiring up the Animation demo app in Kotlin
Frequently asked questions
Summary
20. Drawing Graphics
Understanding the Canvas class
Getting started drawing with Bitmap, Canvas, and ImageView
Canvas and Bitmap
Paint
ImageView and Activity
Canvas, Bitmap, Paint, and ImageView – a quick summary
Using the Canvas class
Preparing the instances of the required classes
Initializing the objects
Setting the Activity content
The Canvas Demo app
Creating a new project
Coding the Canvas demo app
Exploring the Bitmap initialization
Drawing on the screen
Explaining Color.argb
The Android coordinate system
Plotting and drawing
Creating bitmap graphics with the Bitmap class
Manipulating bitmaps
What is a bitmap?
The Matrix class
Inverting a bitmap to face the opposite direction
Rotating the bitmap to face up and down
The Bitmap manipulation demo app
Adding the Bob graphic to the project
Frequently asked question
Summary
21. Threads and Starting the Live Drawing App
Creating the Live Drawing project
Looking ahead at the Live Drawing app
Coding the MainActivity class
Coding the LiveDrawingView class
Adding the properties
Coding the draw function
Adding the printDebuggingText function
Understanding the draw function and the SurfaceView class
The game loop
Threads
Problems with threads
Implementing the game loop with a thread
Implementing Runnable and providing the run function
Coding the thread
Starting and stopping the thread
Using the Activity lifecycle to start and stop the thread
Coding the run function
Running the app
Summary
22. Particle Systems and Handling Screen Touches
Adding custom buttons to the screen
Implementing a particle system effect
Coding the Particle class
Coding the ParticleSystem class
Spawning particle systems in the LiveDrawingView class
Handling touches
Coding the onTouchEvent function
Finishing the HUD
Running the app
Summary
23. Android Sound Effects and the Spinner Widget
The SoundPool class
Initializing SoundPool
Loading sound files into memory
Playing a sound
Stopping a sound
Sound demo app introducing the Spinner widget
Making sound effects
Laying out the sound demo UI
Coding the Sound demo
Summary
24. Design Patterns, Multiple Layouts, and Fragments
Introducing the model-view-controller pattern
Model
View
Controller
Android design guidelines
Real-world apps
Device detection mini app
Coding the MainActivity class
Unlocking the screen orientation
Running the app
Configuration qualifiers
The limitation of configuration qualifiers
Fragments
Fragments have a life cycle too
The onCreate function
The onCreateView function
The onAttach and onDetach functions
The onStart, onPause, and onStop functions
Managing fragments with FragmentManager
Our first fragment app
Fragment reality check
Frequently asked question
Summary
25. Advanced UI with Paging and Swiping
The Angry Birds classic swipe menu
Building an image gallery/slider app
Implementing the layout
Coding the PagerAdapter class
Coding the MainActivity class
Running the gallery app
Kotlin companion objects
Building a Fragment Pager/slider app
Coding the SimpleFragment class
The fragment_layout
Coding the MainActivity class
The activity_main layout
Running the fragment slider app
Summary
26. Advanced UI with Navigation Drawer and Fragment
Introducing the NavigationView
Examining the Age Database app
Insert
Delete
Search
Results
Starting the Age Database project
Exploring the auto-generated code and assets
Coding the Fragment classes and their layouts
Creating the empty files for the classes and layouts
Coding the classes
Designing the layouts
Designing content_insert.xml
Designing content_delete.xml
Designing content_search.xml
Designing content_results.xml
Using the Fragment classes and their layouts
Editing the navigation drawer menu
Adding a holder to the main layout
Coding the MainActivity.kt file
Summary
27. Android Databases
Database 101
What is a database?
What is SQL?
What is SQLite?
The SQL syntax primer
SQLite example code
Creating a table
Inserting data into the database
Retrieving data from the database
Updating the database structure
The Android SQLite API
SQLiteOpenHelper and SQLiteDatabase
Building and executing queries
Database cursors
Coding the database class
Coding the Fragment classes to use the DataManager class
Running the Age Database app
Summary
28. A Quick Chat Before You Go
Publishing
Making an app!
Carrying on learning
Carrying on reading
GitHub
StackOverflow
Android user forums
Higher-level study
My other channels
Goodbye and thank you
A. Other Book You May Enjoy
Leave a review - let other readers know what you think
Index

Android Programming with Kotlin for Beginners

Android Programming with Kotlin for Beginners

Copyright © 2019 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Pavan Ramchandani

Acquisition Editor: Larissa Pinto

Content Development Editor: Smit Carvalho

Technical Editor: Surabhi Kulkarni

Copy Editor: Safis Editing

Project Coordinator: Kinjal Bari

Proofreader: Safis Editing

Indexers: Pratik Shirodkar

Graphics: Alishon Mendonsa

Production Coordinator: Arvindkumar Gupta

First published: April 2019

Production reference: 1260419

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78961-540-1

www.packtpub.com

I think that everybody has an app inside of them, and all you need do is work hard enough to get it out of you.

For Jo, Jack, James, Ray, Rita, and Missy.

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionalsLearn better with Skill Plans built especially for youGet a free eBook or video every monthMapt is fully searchableCopy and paste, print, and bookmark content

Packt.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.Packt.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.Packt.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.

Contributors

About the author

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.

About the reviewers

Ashok Kumar S has been working in the mobile development domain for about six years. In his early days, he was a JavaScript and Node developer. With his strong web development skills, he mastered web and mobile development. He is a Google-certified engineer, a speaker at global conferences, such as DroidCon Berlin and MODS, and he also runs a YouTube channel called AndroidABCD for Android developers. He also contributes heavily to open source to improve his e-karma.

He has written books on WearOS programming and the Firebase toolchain. Ashok has also reviewed books on mobile and web development, namely Mastering Junit5, Android Programming for Beginners, and Developing Enterprise Applications Using JavaScript.

Mitchell Wong Ho was born in Johannesburg, South Africa, where he completed his national diploma in electrical engineering. Mitchell's software development career started on embedded systems and then moved to Microsoft desktop/server applications.

Mitchell has been programming in Java since 2000 on J2ME, JEE, desktop, and Android applications, and has more recently been advocating Kotlin for Android.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Preface

Are you trying to start a career in Android programming, but haven't found the right way in? Do you have a great idea for an app, but don't know how to make it a reality? Or maybe you're just frustrated that to learn Android, you must already know Kotlin. If so, then this book is for you.

Android Programming with Kotlin for Beginners will be your guide to creating Android applications from scratch. We will introduce you to all the fundamental concepts of programming in an Android context, from the basics of Kotlin to working with the Android API. All examples are created within Android Studio, the official Android development environment, which helps supercharge your application development process. After this crash course, we'll dive deeper into Android programming, and you'll learn how to create applications with a professional-standard UI through fragments and store your user's data with SQLite. In addition, you'll see how to make your apps multilingual, draw on the screen with a finger, and work with graphics, sound, and animations too.

By the end of this book, you'll be ready to start building your own custom applications in Android and Kotlin.

Who this book is for

This book is for you if you are completely new to Kotlin, Android, or programming and want to make Android applications. This book also acts as a refresher for those who already have some basic experience of using Kotlin on Android to advance their knowledge and make fast progress through the early projects.

What this book covers

Chapter 1, Getting Started with Android and Kotlin, welcomes you to the exciting world of Android and Kotlin. In this first chapter, we won't waste any time before getting started developing Android apps. We will look at what is so great about Android, what Android and Kotlin are, how they work and complement each other, and what that means to us as future developers. Moving on, we will set up the required software so that we can build and deploy a simple first app.

Chapter 2, Kotlin, XML, and the UI Designer, discusses how, at this stage, we have a working Android development environment and we have built and deployed our first app. It is obvious, however, that code autogenerated by Android Studio is not going to make the next top-selling app on Google Play. We need to explore this autogenerated code so that we can begin to understand Android and then learn how to build on this useful template.

Chapter 3, Exploring Android Studio and the Project Structure, takes us through creating and running two more Android projects. The purpose of these exercises is to explore Android Studio and the structure of Android projects more deeply. When we build our apps ready for deployment, the code and the resource files need to be packed away in the APK file – just as they are. Therefore, all the layout files and other resources, which we will be looking at soon, need to be in the correct structures. Fortunately, Android Studio handles this for us when we create a project from a template. However, we still need to know how to find and amend these files, how to add our own and sometimes remove the files created by Android Studio, and how the resource files are interlinked – sometimes with each other and sometimes with the Kotlin code (that is, the autogenerated Kotlin code as well as our own). Along with understanding the composition of our projects, it will also be beneficial to make sure that we get the most from the emulator.

Chapter 4, Getting Started with Layouts and Material Design, builds on what we have already seen; that is, the Android Studio UI designer and a little bit more Kotlin in action. In this hands-on chapter, we will build three more layouts – still quite simple, yet a step up from what we have done so far. Before we get to the hands-on part, we will have a quick introduction to the concept of material design. We will look at another type of layout called LinearLayout and walk through it, using it to create a usable UI. We will take things a step further using ConstraintLayout both to understand constraints and design more complex and precise UI designs. Finally, we will use TableLayout to lay data out in an easily readable table. We will also write some Kotlin code to switch between our different layouts within one app/project. This is the first major app that links together multiple topics into one neat parcel. The app is called Exploring Layouts.

Chapter 5, Beautiful Layouts with CardView and ScrollView, is the last chapter on layouts before we spend some time focusing on Kotlin and object-oriented programming. We will formalize our learning on some of the different attributes we have already seen, and we will also introduce two more cool layouts, ScrollView and CardView. To finish the chapter off, we will run the CardView project on a tablet emulator.

Chapter 6, The Android Lifecycle, will familiarize us with the lifecycle of an Android app. The idea that a computer program has a lifecycle might sound strange at first, but it will soon make sense. The lifecycle is the way that all Android apps interact with the Android OS. In the same way that the lifecycle of humans enables them to interact with the world around them, we have no choice but to interact with the Android lifecycle, and we must be prepared to handle numerous unpredictable events if we want our apps to survive. We will explore the phases of the lifecycle that an app goes through, from creation to destruction, and how this helps us know where to put our Kotlin code, depending on what we are trying to achieve.

Chapter 7, Kotlin Variables, Operators, and Expressions, along with the following chapter, explains the core fundamentals of Kotlin. In fact, we will explore the topics that are the main principles of programming in general. In this chapter, we will focus on the creation and understanding of the data itself, and in the next chapter, we will explore how to manipulate and respond to it.

Chapter 8, Kotlin Decisions and Loops, moves on from variables, and we now understand how to change the values that they hold with expressions, but how can we take a course of action that is dependent upon the value of a variable? We can certainly add the number of new messages to the number of previously unread messages, but how can we, for example, trigger an action within our app when the user has read all their messages? The first problem is that we need a way to test the value of a variable, and then respond when the value falls within a range of values or is equal to a specific value. Another problem that is common in programming is that we need sections of our code to be executed a certain number of times (more than once, or sometimes not at all) depending on the value of variables. To solve the first problem, we will look at making decisions in Kotlin with if, else, and when. To solve the latter, we will look at loops in Kotlin with while, do – while, for, continue, and break. Furthermore, we will learn that, in Kotlin, decisions are also expressions that produce a value.

Chapter 9, Kotlin Functions, explains that functions are the building blocks of our apps. We write functions that do specific tasks, and then call them when we need to execute that specific task. As the tasks we need to perform in our apps will be quite varied, our functions need to cater to this and be very flexible. Kotlin functions are very flexible, more so than the functions of other Android-related languages. We therefore need to spend a whole chapter learning about them. Functions are intimately related to object-oriented programming, and once we understand the basics of functions, we will be in a good position to take on the wider learning of object-oriented programming.

Chapter 10, Object-Oriented Programming, explains that, in Kotlin, classes are fundamental to just about everything and, in fact, just about everything is a class. We have already talked about reusing other people's code, specifically the Android API, but in this chapter, we will really get to grips with how this works and learn about object-oriented programming (OOP) and how to use it.

Chapter 11, Inheritance in Kotlin, shows inheritance in action. In fact, we have already seen it, but now we will examine it more closely, discuss the benefits, and write classes that we inherit from. Throughout the chapter, I will show you several practical examples of inheritance, and at the end of the chapter we will improve our naval battle simulation from the previous chapter and show how we could have saved lots of typing and future debugging by using inheritance.

Chapter 12, Connecting Our Kotlin to the UI and Nullability, fully reveals, by the end of the chapter, the missing link between our Kotlin code and our XML layouts, leaving us with the power to add all kinds of widgets and UI features to our layouts as we have done before, but this time we will be able to control them through our code. In this chapter, we will take control of some simple UI elements, such as Button and TextView, and, in the next chapter, we will take things further and manipulate a whole range of UI elements. To enable us to understand what is happening, we need to find out a bit more about the memory in an app, and two areas of it in particular – the Stack and the Heap.

Chapter 13, Bringing Android Widgets to Life, discusses that since we now have a good overview of both the layout and coding of an Android app, as well as our newly acquired insight into object-oriented programming (OOP) and how we can manipulate the UI from our Kotlin code, we are ready to experiment with more widgets from the Android Studio palette. At times, OOP is a tricky thing, and this chapter introduces some topics that can be awkward for beginners. However, by gradually learning these new concepts and practicing them repeatedly, they will, over time, become our friend. In this chapter, we will diversify a lot by going back to the Android Studio palette and looking at half a dozen widgets that we have either not seen at all or have not used fully yet. Once we have done so, we will put them all into a layout and practice manipulating them with our Kotlin code.

Chapter 14, Android Dialog Windows, explains how to present the user with a pop-up dialog window. We can then put all that we know into the first phase of our first multi-chapter app, Note to self. We will then learn about new Android and Kotlin features in this chapter and the four following chapters (up to Chapter 18, Localization), and then use our newly-acquired knowledge to enhance the Note to self app.

Chapter 15, Handling Data and Generating Random Numbers, shows that we are making good progress. We have a rounded knowledge of both the Android UI options and the basics of Kotlin. In the previous few chapters, we started bringing these two areas together and we have manipulated the UI, including some new widgets, using Kotlin code. However, while building the Note to self app, we have stumbled upon a couple of gaps in our knowledge. In this chapter, we will fill in the first of these blanks, and then, in the next chapter, we will use this new information to progress with the app. We currently have no way of managing large amounts of related data. Aside from declaring, initializing, and managing dozens, hundreds, or even thousands of properties or instances, how will we let the users of our app have more than one note? We will also take a quick diversion to learn about random numbers.

Chapter 16, Adapters and Recyclers, first takes us through the theory of adapters and lists. We will then look at how we can use a RecyclerAdapter instance in Kotlin code and add a RecyclerView widget to the layout, which acts as a list for our UI, and then, through the apparent magic of the Android API, bind them together so that the RecyclerView instance displays the contents of the RecyclerAdapter instance and allows the user to scroll through the contents of an ArrayList instance full of Note instances. You have probably guessed that we will be using this technique to display our list of notes in the Note to self app.

Chapter 17, Data Persistence and Sharing, goes through a couple of different ways to save data to an Android device's permanent storage. Also, for the first time, we will add a second Activity instance to our app. It often makes sense when implementing a separate "screen", such as a "Settings" screen, in our app to do so in a new Activity instance. We could go to the trouble of hiding the original UI and then showing the new UI in the same Activity, as we did in Chapter 4, Getting Started with Layouts and Material Design, but this would quickly lead to confusing and error-prone code. So, we will see how to add another Activity instance and navigate the user between them.

Chapter 18, Localization, is quick and simple, but what we will learn to do can make your app accessible to millions of potential users. We will see how to add additional languages, and we will see why adding text the correct way via String resources benefits us when it comes to adding multiple languages.

Chapter 19, Animations and Interpolations, explores how we can use the Animation class to make our UI a little less static and a bit more interesting. As we have come to expect, the Android API will allow us to do some quite advanced things with relatively straightforward code, and the Animation class is no different.

Chapter 20, Drawing Graphics, is about the Android Canvas class and some related classes, such as Paint, Color, and Bitmap. When combined, these classes have great power when it comes to drawing on the screen. Sometimes, the default UI provided by the Android API isn't what we need. If we want to make a drawing app, draw graphs, or perhaps make a game, we need to take control of every pixel that the Android device has to offer.

Chapter 21, Threads and Starting the Live Drawing App, gets us started on our next app. This app will be a kid's-style drawing app where the user can draw on the screen using their finger. The drawing app that we create will be slightly different, however. The lines that the user draws will be comprised of particle systems that explode into thousands of pieces. We will call the project Live Drawing.

Chapter 22, Particle Systems and Handling Screen Touches, builds on our real-time system that we implemented in the previous chapter using a thread. In this chapter, we will create the entities that will exist and evolve in this real-time system as if they have a mind of their own and form the appearance of the drawings that the user can create. We will also see how the user implements these entities by learning how to respond to interaction with the screen. This is different to interacting with a widget in a UI layout.

Chapter 23, Android Sound Effects and the Spinner Widget, explores the SoundPool class and the different ways we use it depending on whether we just want to play sounds or go further and keep track of the sounds we are playing. At this point, we can then put everything we have learned into producing a cool sound demo app, which will also introduce us to a new UI widget; the Spinner.

Chapter 24, Design Patterns, Multiple Layouts, and Fragments, shows just how far we have come the start, when we were just setting up Android Studio. Back then, we went through everything step by step, but as we have proceeded, we have tried to show not just how to add x to y, or feature a to app b, but to enable you to use what you have learned in your own way in order to bring your own ideas to life. This chapter is more about your future apps than anything in the book so far. We will look at a few aspects of Kotlin and Android that you can use as a framework or template for making ever more exciting and complex apps at the same time as keeping the code manageable.

Chapter 25, Advanced UI with Paging and Swiping, explains that paging is the act of moving from page to page, and, on Android, we do this by swiping a finger across the screen. The current page then transitions in a direction and speed to match the finger movement. It is a useful and practical way to navigate around an app, but perhaps even more than this, it is an extremely satisfying visual effect for the user. Also, as with RecyclerView, we can selectively load just the data required for the current page and perhaps the data for the previous and next pages in anticipation. The Android API, as you would have come to expect, has a few solutions for achieving paging in a quite simple manner.

Chapter 26, Advanced UI with Navigation Drawer and Fragment, explores what is (arguably) the most advanced UI. NavigationView, or the navigation drawer (because of the way it slides out its content), can be created simply by choosing it as a template when you create a new project. We will do just that, and then we will examine the auto-generated code and learn how to interact with it. We will then use everything we know about the Fragment class to populate each of the "drawers" with different behaviors and views. Then, in the next chapter, we will learn about databases to add some new functionality to each Fragment.

Chapter 27, Android Databases, explains that if we are going to make apps that offer our users significant features, then almost certainly we are going to need a way to manage, store, and filter significant amounts of data. It is possible to efficiently store very large amounts of data with JSON, but when we need to use that data selectively rather than simply restricting ourselves to the options of "save everything" and "load everything," we need to think about which other options are available. As so often, it makes sense to use the solutions provided in the Android API. As we have seen, JSON and SharedPreferences classes have their place but at some point, we need to move on to using real databases for real-world solutions. Android uses the SQLite database management system and, as you would expect, there is an API to make it as easy as possible.

Chapter 28, A Quick Chat Before You Go, contains a few ideas and pointers that you might like to look at before rushing off and making your own apps.

To get the most out of this book

To succeed with this book, you don't need any experience whatsoever. If you are confident with your operating system of choice (Windows, Mac, or Linux), you can learn to make Android apps while learning the Kotlin programming language. Learning to develop professional quality apps is a journey that anybody can embark upon and stay on for as long as they want.

If you do have previous programming (Kotlin, Java, or any other language), Android, or other development experience, then you will make faster progress with the earlier chapters.

Download the example code files

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 emailed directly to you.

You can download the code files by following these steps:

Log in or register at http://www.packtpub.com.Select the SUPPORT tab.Click on Code Downloads & Errata.Enter the name of the book in the Search box and follow the on-screen instructions.

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

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Android-Programming-with-Kotlin-for-Beginners. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789615401_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example; "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

<TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="TextView" />

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout>

Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: "If not, click on the Logcat tab"

Note

Warnings or important notes appear like this.

Tip

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected], and mention the book's title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book we would be grateful if you would report this to us. Please visit, http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Chapter 1. Getting Started with Android and Kotlin

Welcome to the exciting world of Android and Kotlin! In this first chapter, we won't waste any time before getting started developing Android apps.

We will look at what is so great about Android, what Android and Kotlin are, how they work and complement each other, and what that means to us as future developers. Moving on, we will set up the required software, so that we can build and deploy a simple first app.

In this chapter, we will cover the following topics:

Learning how Kotlin and Android work togetherSetting up our development environment, Android StudioLearning what makes an android appLearning about KotlinBuilding our very first Android appDeploying an Android emulatorRunning our app on an Android emulator and a real device

This is a lot to get through, so let's get started.

Why use Kotlin and Android?

When Android first arrived in 2008, it was a bit drab compared to the much more stylish iOS on the Apple iPhone/iPad. But, quite quickly, through a variety of handset offers that struck a chord with practical, price-conscious consumers, as well as those who are fashion-conscious and tech-savvy, Android user numbers exploded.

For many, myself included, developing for Android is the most rewarding pastime and business, bar none.

Quickly putting together a prototype of an idea, refining it, and then deciding to run with it and wire it up into a fully-fledged app, is such an exciting and rewarding process. Any programming can be fun – I have been programming all my life – but creating for Android is somehow extraordinarily rewarding.

Defining exactly why this is the case is quite difficult. Perhaps it is the fact that the platform is free and open. You can distribute your apps without needing the permission of a big controlling corporation – nobody can stop you. And, at the same time, you have well-established, corporate-controlled mass markets, such as Amazon Appstore and Google Play.

It is more likely, however, that the reason that developing for Android gives such a good feeling is the nature of the devices themselves. They are deeply personal. You can develop apps that interact with people's lives, which educate, entertain, tell a story, and so on, and it is there in their pocket ready to go – in the home, in the workplace, or on holiday.

You can certainly build something bigger for the desktop but knowing that thousands (or millions) of people are carrying your work in their pockets and sharing it with friends is more than just a buzz.

No longer is developing apps considered geeky, nerdy, or reclusive. In fact, developing for Android is considered highly skillful, and the most successful developers are hugely admired, even revered.

If all this fluffy, spiritual stuff doesn't mean anything to you, then that's fine too; developing for Android can make you a living, or even make you wealthy. With the continued growth of device ownership, the ongoing increase in CPU and GPU power, and the non-stop evolution of the Android operating system itself, the need for professional app developers is only going to grow.

In short, the best Android developers – and, more importantly, the Android developers with the best ideas and the most determination – are in greater demand than ever. Nobody knows who these future Android app developers are, and they might not even have written their first line of code yet.

So, why isn't everybody an Android developer? Obviously, not everybody will share my enthusiasm for the thrill of creating software that can help make people's lives better, but I am guessing that, because you are reading this, you might.

The beginner's first stumbling block

Unfortunately, for those who do share my enthusiasm, there is a kind of glass wall on the path of progress that frustrates many aspiring Android developers.

Android asks aspiring developers to choose from three programming languages to make apps. Every Android book, even those aimed at so-called beginners, assumes that readers have at least an intermediate level of Kotlin, C++, or Java, and most need an advanced level. So, good-to-excellent programming knowledge is considered a prerequisite for learning Android.

Unfortunately, learning these languages in a completely different context to Android can sometimes be a little dull, and much of what you learn is not directly transferable into the world of Android either. You can see why beginners to Android are often put off.

It doesn't need to be like this. In this book, I have carefully placed all the Kotlin topics that you would learn in a thick and weighty Kotlin-only beginner's tome, and reworked them into three multi-chapter apps and more than a dozen quick mini-apps, starting from a simple memo app, progressing to a cool drawing app and a database app.

If you want to become a professional Android developer, or just want to have more fun when learning Kotlin and Android, this book will help.

How Kotlin and Android work together

The Android Software Development Kit (SDK) is largely written in Java, because Kotlin is the new kid on the block; but when we tell Android Studio to turn our Kotlin code into a working app, it is merged together with the Java from the SDK in an intermediate form before being converted into a format called DEX code, which the Android device uses to convert into a running app. This is seamless to us as developers, but it is worth knowing (and, perhaps, is quite interesting) to know what is going on behind the scenes.

Whether you have programmed your app in Kotlin or Java, the resulting DEX code is the same. However, there are some significant advantages to working with Kotlin.

Kotlin is named after an island near St Petersburg, Russia. Kotlin is very similar to Apple's Swift language, so learning Kotlin now will stand you in very good stead for learning iPhone/iPad development.

Kotlin is the most succinct language, and therefore is the least error-prone, which is great for beginners. Kotlin is also the most fun language, mainly because the succinctness means you can get results faster and with less code. Google considers Kotlin an official (first-class) Android language. There are some other advantages to Kotlin that make it less error-prone and less likely to make mistakes that cause crashes. We will discover the details of these advantages as we proceed.

Loads of the most advanced, innovative, and popular apps were coded using Kotlin. Just a few examples include Kindle, Evernote, Twitter, Expedia, Pinterest, and Netflix.

Before we start our Android quest, we need to understand how Android and Kotlin work together. After we write a program for Android, either in Java or Kotlin, we click a button and our code is transformed into another form, a form that is understood by Android. This other form is called Dalvik Executable, or DEX code, and the transformation process is called compiling. When the app is installed on a device, the DEX code is transformed again by the operating system into an optimized executable state.

Note

We will see this process in action right after we set up our development environment later on in the chapter.

Android is a complex system, but you do not need to understand it in depth to be able to start making amazing apps.

Tip

A full understanding will come after using and interacting with it over time.

To get started, we only need to understand the basics. Android runs on a specially adapted version of the Linux operating system. So, what the user sees of Android is just an app running on yet another operating system.

Android is a system within a system. The typical Android user doesn't see the Linux operating system, and most probably doesn't even know it is there.

One purpose of this is to hide the complexity and diversity of the hardware and software that Android runs on, but, at the same time, exposing all its useful features. The exposure of these features works in two ways:

First, the operating system itself must have full access to the hardware, which it does.Second, this access must be programmer-friendly and easy to use, and it is because of the Android application programming interface (API).

Let's continue by looking further into the Android API.

The Android API

The Android API is code that makes it easy to do exceptional things. A simple analogy could be drawn with a machine, perhaps a car. When you press on the accelerator, a whole bunch of things happen under the hood. We don't need to understand combustion or fuel pumps, because some smart engineer has made an interface for us; in this case, a mechanical interface – the accelerator pedal.

For example, the following line of code probably looks a little intimidating at this stage in the book, but it serves as a good example of how the Android API helps us:

locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)

Once you learn that this single line of code searches for available satellites in space, communicates with them in their orbits around the Earth, and then retrieves your precise latitude and longitude on the surface of the planet, it becomes easy to glimpse the power and depth of the Android API.

That code does look a little challenging, even mind-boggling at this stage of the book, but imagine trying to talk to a satellite some other way!

The Android API has a whole bunch of code that has already been written for us to use as we like.

The question we must ask, and the one this book tries to answer, is as follows: how do we use all this code to do cool stuff? Or, to frame the question to fit the earlier analogy: how do we find and manipulate the pedals, steering wheel, and, most importantly, the sunroof of the Android API?

The answer to this question is the Kotlin programming language, and the fact that Kotlin was designed to help programmers handle complexity, avoid mistakes, and make fast progress. Let's look deeper into Kotlin and object-oriented programming (OOP).

Kotlin is object-oriented

Kotlin is an object-oriented language. This means that it uses the concept of reusable programming objects. If this sounds like technical jargon, another analogy will help. Kotlin enables us and others (like the Android API development team) to write code that can be structured based on real-world things, and here is the important part – it can be reused.

So, using the car analogy, we could ask the following question: if a manufacturer makes more than one car in a day, do they redesign every part for every car that comes off the production line?

The answer, of course, is no. They get highly skilled engineers to develop exactly the right components, honed, refined, and improved over years. Then, those same components are reused again and again, as well as being occasionally improved.

If you are going to be fussy about my analogy, then you can point out that each of the car's components must still be built from the raw materials using real-life engineers or robots. This is true.

What software engineers do when they write their code is build a blueprint for an object. We then create an object from their blueprint using code and once we have that object, we can configure it, use it, combine it with other objects, and more besides.

Furthermore, we can design blueprints ourselves and make objects from them. The compiler then transforms (manufactures) our bespoke creation into DEX code. Hey presto! We have an Android app.

In Kotlin, a blueprint is called a class. When a class is transformed into a real working "thing," we call it an object or an instance of the class.

Note

Objects in short.

We could go on making analogies all day long. As far as we care at this point, Kotlin (and most modern programming languages) is a language that allows us to write code once that can then be used repeatedly.

This is very useful because it saves us time, and allows us to use other people's code to perform tasks we might otherwise not have the time or knowledge to write for ourselves. Most of the time, we do not even need to see this code, or even know how it does its work!

One last analogy. We just need to know how to use that code, just as we need to learn how to drive a car.

So, some smart software engineers up at Android HQ write a desperately complex program that can talk to satellites, and as a result of this, in a single line of code, we can get our location on the surface of the planet. Nice.

Most of the Android API is written in another language (Java), but this doesn't matter to us as we have full access to the functionality (coded in Java) while using the more succinct Kotlin. Android Studio and the Kotlin compiler handle the complexities behind the scenes.

The software engineers have considered how they can make this code useful to all Android programmers who want to make amazing apps that use users' locations to do cool things. One of the things they will do is make features, such as getting the device's location in the world into a simple one-line task.

So, the single line of code we saw previously sets in action many more lines of code that we don't see, and don't need to see. This is an example of using somebody else's code to make our code infinitely simpler.

Tip

If the fact that you don't have to see all the code is a disappointment to you, then I understand how you feel. Some of us, when we learn about something, want to learn every intricate detail. If this is you, then be reassured that the best place to start learning how the Android API works internally is to use it as the API programmers intended. And, throughout the book, I will regularly point out further learning opportunities where you can find out the inner workings of the Android API. Also, we will be writing classes that are themselves reusable, kind of like our own API, except that our classes will focus on what we want our app to do.

Welcome to the world of OOP. I will constantly refer to OOP in every chapter, and there will be a big reveal in Chapter 10, Object-Oriented Programming.

Run that by me again – what, exactly, is Android?

To get things done on Android, we write code of our own, which also uses the code of the Android API. This is then compiled into DEX code, and the rest is handled by the Android device, which, in turn, runs on an underlying operating system called Linux, which handles the complex and extremely diverse range of hardware that is the different Android devices.

The manufacturers of Android devices and of the individual hardware components obviously know this too, and they write advanced software called drivers that ensure that their hardware (for example, CPU, GPU, GPS receivers, memory chips, and hardware interfaces) can run on the underlying Linux operating system.

The DEX code (along with some other resources) are placed in a bundle of files called an Android application package (APK), and this is what the device needs to run our app.

Tip

It is not necessary to remember the details of the steps that our code goes through when it interacts with the hardware. It is enough just to understand that our code goes through some automated processes to become the app that we will publish to the Google Play store.

The next question is: where exactly does all this coding and compiling into DEX code, along with APK packaging, take place? Let's look at the development environment that we will be using.

Android Studio

A development environment is a term that refers to having everything you need to develop, set up and ready to go in one place.

There is an entire range of tools needed to develop for Android, and we also need the Android API, of course. This whole suite of requirements is collectively known as the SDK. Fortunately, downloading and installing a single application will give us these things all bundled together. The application is called Android Studio.

Android Studio is an integrated development environment (IDE) that will take care of all the complexities of compiling our code and linking with the Android API. Once we have installed Android Studio, we can do everything we need inside this single application, and put to the back of our minds many of the complexities we have been discussing.

Tip

Over time, these complexities will become second nature. It is not necessary to master them immediately to make further progress.

So, we had better get our hands on Android Studio.

Setting up Android Studio

Setting up Android Studio is quite straightforward, if a little time-consuming. Grab some refreshments and get started with the following steps:

Visit developer.android.com/studio/index.html. Click the big DOWNLOAD ANDROID STUDIO button to proceed:Accept the terms and conditions by checking the checkbox, and then click the DOWNLOAD ANDROID STUDIO FOR WINDOWS button:When the