Book Image

Android Programming with Kotlin for Beginners

By : John Horton
5 (1)
Book Image

Android Programming with Kotlin for Beginners

5 (1)
By: John Horton

Overview of this book

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.
Table of Contents (33 chapters)
Android Programming with Kotlin for Beginners
Contributors
Preface
Index

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, dowhile, 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:

  1. Log in or register at http://www.packtpub.com.

  2. Select the SUPPORT tab.

  3. Click on Code Downloads & Errata.

  4. 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 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/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.

Note

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.