How to Build Android Apps with Kotlin. - Alex Forrester - E-Book

How to Build Android Apps with Kotlin. E-Book

Alex Forrester

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

Are you keen to get started building Android 11 apps, but don’t know where to start? How to Build Android Apps with Kotlin is a comprehensive guide that will help kick-start your Android development practice.

This book starts with the fundamentals of app development, enabling you to utilize Android Studio and Kotlin to get started building Android projects. You'll learn how to create apps and run them on virtual devices through guided exercises. Progressing through the chapters, you'll delve into Android’s RecyclerView to make the most of lists, images, and maps, and see how to fetch data from a web service.

Moving ahead, you'll get to grips with testing, learn how to keep your architecture clean, understand how to persist data, and gain basic knowledge of the dependency injection pattern. Finally, you'll see how to publish your apps on the Google Play store.

You'll work on realistic projects that are split up into bitesize exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way. You'll build apps to create quizzes, read news articles, check weather reports, store recipes, retrieve movie information, and remind you where you parked your car.

By the end of this book, you'll have the skills and confidence to build your own creative Android applications using Kotlin.

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

EPUB
MOBI

Seitenzahl: 664

Veröffentlichungsjahr: 2021

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.



How to Build Android Apps with Kotlin

A hands-on guide to developing, testing, and publishing your first apps with Android

Alex Forrester, Eran Boudjnah, Alexandru Dumbravan, and Jomar Tigcal

How to Build Android Apps with Kotlin

Copyright © 2021 Packt Publishing

All rights reserved. No part of this course 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 course to ensure the accuracy of the information presented. However, the information contained in this course is sold without warranty, either express or implied. Neither the authors, 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 course.

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

Authors: Alex Forrester, Eran Boudjnah, Alexandru Dumbravan, and Jomar Tigcal

Reviewers: Niharika Arora, Gaurav Chandorkar, and Kaushal Dhruw

Managing Editor: Anushree Arun Tendulkar

Acquisitions Editors: Royluis Rodrigues and Anindya Sil

Production Editor: Salma Patel

Editorial Board: Megan Carlisle, Mahesh Dhyani, Heather Gopsill, Manasa Kumar, Alex Mazonowicz, Monesh Mirpuri, Bridget Neale, Abhishek Rane, Brendan Rodrigues, Ankita Thakur, Nitesh Thakur, and Jonathan Wray

First published: February 2021

Production reference: 2160321

ISBN: 978-1-83898-411-3

Published by Packt Publishing Ltd.

Livery Place, 35 Livery Street

Birmingham B3 2PB, UK

Table of Contents

Preface

1. Creating Your First App

Introduction

Creating an Android Project with Android Studio

Exercise 1.01: Creating an Android Studio Project for Your App

Setting Up a Virtual Device and Running Your App

Exercise 1.02: Setting Up a Virtual Device and Running Your App on It

The Android Manifest

Exercise 1.03: Configuring the Android Manifest Internet Permission

Using Gradle to Build, Configure, and Manage App Dependencies

Project-Level build.gradle file

App-Level build.gradle

Exercise 1.04: Exploring how Material Design is used to theme an app

Android Application Structure

Exercise 1.05: Adding Interactive UI Elements to Display a Bespoke Greeting to the User

Accessing Views in layout files

Further Input Validation

Activity 1.01: Producing an App to Create RGB Colors

Summary

2. Building User Screen Flows

Introduction

The Activity Lifecycle

Exercise 2.01: Logging the Activity Callbacks

Saving and Restoring the Activity State

Exercise 2.02: Saving and Restoring the State in Layouts

Exercise 2.03: Saving and Restoring the State with Callbacks

Activity Interaction with Intents

Exercise 2.04: An Introduction to Intents

Exercise 2.05: Retrieving a Result from an Activity

Intents, Tasks, and Launch Modes

Exercise 2.06: Setting the Launch Mode of an Activity

Activity 2.01: Creating a Login Form

Summary

3. Developing the UI with Fragments

Introduction

The Fragment Lifecycle

onAttach

onCreate

onCreateView

onViewCreated

onActivityCreated

onStart

onResume

onPause

onStop

onDestroyView

onDestroy

onDetach

Exercise 3.01: Adding a Basic Fragment and the Fragment Lifecycle

Exercise 3.02: Adding Fragments Statically to an Activity

Static Fragments and Dual-Pane Layouts

Exercise 3.03: Dual-Pane Layouts with Static Fragments

Dynamic Fragments

Exercise 3.04: Adding Fragments Dynamically to an Activity

Jetpack Navigation

Exercise 3.05: Adding a Jetpack Navigation Graph

Activity 3.01: Creating a Quiz on the Planets

Summary

4. Building App Navigation

Introduction

Navigation Overview

Navigation Drawer

Exercise 4.01: Creating an App with a Navigation Drawer

Bottom Navigation

Exercise 4.02: Adding Bottom Navigation to Your App

Tabbed Navigation

Exercise 4.03: Using Tabs for App Navigation

Activity 4.01: Building Primary and Secondary App Navigation

Summary

5. Essential Libraries: Retrofit, Moshi, and Glide

Introduction

Fetching Data from a Network Endpoint

Exercise 5.01: Reading Data from an API

Parsing a JSON Response

Exercise 5.02: Extracting the Image URL from the API Response

Loading Images from a Remote URL

Exercise 5.03: Loading the Image from the Obtained URL

Activity 5.01: Displaying the Current Weather

Summary

6. RecyclerView

Introduction

Adding RecyclerView to Our Layout

Exercise 6.01: Adding an Empty RecyclerView to Your Main Activity

Populating the RecyclerView

Exercise 6.02: Populating Your RecyclerView

Responding to Clicks in RecyclerView

Exercise 6.03: Responding to Clicks

Supporting Different Item Types

Exercise 6.04: Adding Titles to RecyclerView

Swiping to Remove Items

Exercise 6.05: Adding Swipe to Delete Functionality

Adding Items Interactively

Exercise 6.06: Implementing an "Add A Cat" Button

Activity 6.01: Managing a List of Items

Summary

7. Android Permissions and Google Maps

Introduction

Requesting Permissions from the User

Exercise 7.01: Requesting the Location Permission

Showing a Map of the User's Location

Exercise 7.02: Obtaining the User's Current Location

Map Clicks and Custom Markers

Exercise 7.03: Adding a Custom Marker Where the Map Was Clicked

Activity 7.01: Creating an App to Find the Location of a Parked Car

Summary

8. Services, WorkManager, and Notifications

Introduction

Starting a Background Task Using WorkManager

Exercise 8.01: Executing Background Work with the WorkManager Class

Background Operations Noticeable to the User – Using a Foreground Service

Exercise 8.02: Tracking Your SCA's Work with a Foreground Service

Activity 8.01: Reminder to Drink Water

Summary

9. Unit Tests and Integration Tests with JUnit, Mockito, and Espresso

Introduction

JUnit

Android Studio Testing Tips

Mockito

mockito-kotlin

Exercise 9.01: Testing the Sum of Numbers

Integration Tests

Robolectric

Espresso

Exercise 9.02: Double Integration

UI Tests

Exercise 9.03: Random Waiting Times

Test-Driven Development

Exercise 9.04: Using TDD to Calculate the Sum of Numbers

Activity 9.01: Developing with TDD

Summary

10. Android Architecture Components

Introduction

ViewModel and LiveData

ViewModel

LiveData

Exercise 10.01: Creating a Layout with Configuration Changes

Exercise 10.02: Adding a ViewModel

Exercise 10.03: Sharing our ViewModel between the Fragments

Exercise 10.04: Adding LiveData

Room

Entities

DAO

Setting Up the Database

Third-Party Frameworks

Exercise 10.05: Making a Little Room

Customizing Life Cycles

Exercise 10.06: Reinventing the Wheel

Activity 10.01: Shopping Notes App

Summary

11. Persisting Data

Introduction

Repository

Exercise 11.01: Creating a Repository

Exercise 11.02: Adding Error Handling

Preferences

SharedPreferences

Exercise 11.03: Wrapping SharedPreferences

PreferenceFragment

Exercise 11.04: Customized Settings

Files

Internal Storage

External Storage

FileProvider

Storage Access Framework (SAF)

Asset Files

Exercise 11.05: Copying Files

Scoped Storage

Camera and Media Storage

Exercise 11.06: Taking Photos

Activity 11.01: Dog Downloader

Summary

12. Dependency Injection with Dagger and Koin

Introduction

Manual DI

Exercise 12.01: Manual Injection

Dagger

Consumers

Providers

Connectors

Qualifiers

Scopes

Subcomponents

Exercise 12.02: Dagger Injection

Dagger Android

Exercise 12.03: Changing Injectors

Koin

Exercise 12.04: Koin Injection

Activity 12.01: Injected Repositories

Activity 12.02: Koin-Injected Repositories

Summary

13. RxJava and Coroutines

Introduction

RxJava

Observables, Observers, and Operators

Schedulers

Adding RxJava to Your Project

Using RxJava in an Android Project

Exercise 13.01: Using RxJava in an Android Project

Modifying Data with RxJava Operators

Exercise 13.02: Using RxJava Operators

Coroutines

Creating Coroutines

Adding Coroutines to Your Project

Exercise 13.03: Using Coroutines in an Android App

Transforming LiveData

Exercise 13.04: LiveData Transformations

Coroutines Channels and Flows

RxJava versus Coroutines

Activity 13.01: Creating a TV Guide App

Summary

14. Architecture Patterns

Introduction

MVVM

Data Binding

Exercise 14.01: Using Data Binding in an Android Project

Retrofit and Moshi

The Repository Pattern

Exercise 14.02: Using Repository with Room in an Android Project

WorkManager

Exercise 14.03: Adding WorkManager to an Android Project

Activity 14.01: Revisiting the TV Guide App

Summary

15. Animations and Transitions with CoordinatorLayout and MotionLayout

Introduction

Activity Transitions

Adding Activity Transitions through XML

Adding Activity Transitions through Code

Starting an Activity with an Activity Transition

Exercise 15.01: Creating Activity Transitions in an App

Adding a Shared Element Transition

Starting an Activity with the Shared Element Transition

Exercise 15.02: Creating the Shared Element Transition

Animations with CoordinatorLayout

Animations with MotionLayout

Adding MotionLayout

Creating Animations with MotionLayout

Exercise 15.03: Adding Animations with MotionLayout

The Motion Editor

Debugging MotionLayout

Modifying the MotionLayout Path

Exercise 15.04: Modifying the Animation Path with Keyframes

Activity 15.01: Password Generator

Summary

16. Launching Your App on Google Play

Introduction

Preparing Your Apps for Release

Versioning Apps

Creating a Keystore

Exercise 16.01: Creating a Keystore in Android Studio

Storing the Keystore and Passwords

Signing Your Apps for Release

Exercise 16.02: Creating a Signed APK

Android App Bundle

Exercise 16.03: Creating a Signed App Bundle

App Signing by Google Play

Creating a Developer Account

Uploading an App to Google Play

Creating a Store Listing

App Details

Graphic Assets

Preparing the Release

APK/App Bundle

Rolling Out a Release

Managing App Releases

Release Tracks

Feedback Channel and Opt-in Link

Internal Testing

Closed Testing

Open Testing

Staged Rollouts

Managed Publishing

Activity 16.01: Publishing an App

Summary

Preface

About the Book

Android has ruled the app market for the past decade, and developers are increasingly looking to start building their own Android apps. How to Build Android Apps with Kotlin starts with the building blocks of Android development, teaching you how to use Android Studio, the integrated development environment (IDE) for Android, with the programming language Kotlin for app development. Then, you'll learn how to create apps and run them on virtual devices through guided exercises. You'll cover the fundamentals of Android development, from structuring an app to building out the UI with Activities and Fragments and various navigation patterns. Progressing through the chapters, you'll delve into Android's RecyclerView to make the most of displaying lists of data and become comfortable with fetching data from a web service and handling images. You'll then learn about mapping, location services, and the permissions model before working with notifications and how to persist data. Moving on, you'll get to grips with testing, covering the full spectrum of the test pyramid. You'll also learn how AAC (Android Architecture Components) are used to cleanly structure your code and explore various architecture patterns and the benefits of dependency injection. The core libraries of RxJava and Coroutines are covered for asynchronous programming. The focus then returns to the UI, demonstrating how to add motion and transitions when users interact with your apps. Towards the end, you'll build an interesting app to retrieve and display popular movies from a movie database, and then see how to publish your apps on Google Play. By the end of this book, you'll have the skills and confidence needed to build fully-fledged Android apps using Kotlin.

ABOUT THE AUTHORS

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.

Alexandru Dumbravan started Android development in 2011 working for a digital agency. In 2016, he moved to London, working mainly in the FinTech sector. Over the course of his career, he has had the opportunity to analyze and integrate many different technologies on Android devices, from well-known applications like Facebook login, to lesser-known tech, like proprietary network protocols.

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He has worked on various stages of app development for small startups and large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada, with his wife Celine.

Audience

If you want to build your own Android apps using Kotlin but are unsure of how to begin, then this book is for you. A basic understanding of the Kotlin programming language will help you grasp the topics covered in this book more quickly.

About the Chapters

Chapter 1, Creating Your First App, shows how to use Android Studio to build your first Android app. Here you will create an Android Studio project and understand what it's made up of, and explore the tools necessary for building and deploying an app on a virtual device. You will also learn about the structure of an Android app.

Chapter 2, Building User Screen Flows, dives into the Android ecosystem and the building blocks of an Android application. Concepts such as activities and their lifecycle, intents, and tasks will be introduced, as well as restoring state and passing data between screens or activities.

Chapter 3, Developing the UI with Fragments, teaches you the fundamentals of using fragments for the user interface of an Android application. You will learn how to use fragments in multiple ways to build application layouts for phones and tablets, including using the Jetpack Navigation component.

Chapter 4, Building App Navigation, goes through the different types of navigation in an application. You will learn about navigation drawers with sliding layouts, bottom navigation, and tabbed navigation.

Chapter 5, Essential Libraries: Retrofit, Moshi, and Glide, gives you an insight into how to build apps that fetch data from a remote data source with the use of the Retrofit library and the Moshi library to convert data into Kotlin objects. You will also learn about the Glide library, which loads remote images into your app.

Chapter 6, RecyclerView, introduces the concept of building lists and displaying them with the help of the RecyclerView widget.

Chapter 7, Android Permissions and Google Maps, presents the concept of permissions and how to request them from the user in order for your app to execute specific tasks, as well as introducing you to the Maps API.

Chapter 8, Services, WorkManager, and Notifications, details the concept of background work in an Android app and how you can have your app execute certain tasks in a way that is invisible to the user, as well as covering how to show a notification of this work.

Chapter 9, Unit Tests and Integration Tests with JUnit, Mockito, and Espresso, teaches you about the different types of tests for an Android application, what frameworks are used for each type of test, and the concept of test-driven development.

Chapter 10, Android Architecture Components, gives an insight into components from the Android Jetpack libraries, such as LiveData and ViewModel, which help you structure your code, and Room, which allows you to persist data on a device in a database.

Chapter 11, Persisting Data, shows you the various ways to store data on a device, from SharedPreferences to files. The Repository concept will also be introduced, giving you an idea of how to structure your app in different layers.

Chapter 12, Dependency Injection with Dagger and Koin, explains the concept of dependency injection and the benefits it provides to an application. Frameworks such as Dagger and Koin are introduced to help you manage your dependencies.

Chapter 13, RxJava and Coroutines, introduces you to doing background operations and data manipulations with RxJava and Coroutines. You'll also learn about manipulating and displaying data using RxJava operators and LiveData transformation.

Chapter 14, Architecture Patterns, explains the architecture patterns you can use to structure your Android projects to separate them into different components with distinct functionality. These make it easier for you to develop, test, and maintain your code.

Chapter 15, Animations and Transitions with CoordinatorLayout and MotionLayout, discusses how to enhance your apps with animations and transitions with CoordinatorLayout and MotionLayout.

Chapter 16, Launching Your App on Google Play, concludes this book by showing you how to publish your apps on Google Play: from preparing a release, to creating a Google Play Developer account, to finally launching your app.

Conventions

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:

"You can find it in the main project window under MyApplication | app | src | main."

A block of code is set as follows:

<resources>

    <string name="app_name">My Application</string>

</resources>

In some cases, important lines of code are highlighted. These cases are presented as follows:

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="app_name">My Application</string>

    <string name="first_name_text">First name:</string>

    <string name="last_name_text">Last name:</string>

</resources>

Words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this: "Click Finish and your virtual device will be created."

New terms and important words are shown like this: "It is the official Integrated Development Environment (IDE) for Android development, built on JetBrains' IntelliJ IDEA software and developed by the Android Studio team at Google."

Before You Begin

Each great journey begins with a humble step. Before we can do awesome things in Android, we need to be prepared with a productive environment. In this section, we will see how to do that.

Minimum Hardware Requirements

For an optimal learning experience, we recommend the following hardware configuration:

Processor: Intel Core i5 or equivalent or higherMemory: 4 GB RAM minimum; 8 GB RAM recommendedStorage: 4 GB available space

Software Requirements

You'll also need the following software installed in advance:

OS: Windows 7 SP1 64-bit, Windows 8.1 64-bit or Windows 10 64-bit, macOS, or LinuxAndroid Studio 4.1 or higher

Installation and Setup

Before you start this book, you will need to install Android Studio 4.1 (or higher), which is the main tool that you will be using throughout the chapters. You can download Android Studio from https://developer.android.com/studio.

On macOS, launch the DMG file and drag and drop Android Studio into the Applications folder. Once this is done, open Android Studio. On Windows, launch the EXE file. If you're using Linux, unpack the ZIP file into your preferred location. Open your Terminal and navigate to the android-studio/bin/ directory and execute studio.sh. If you see an Import Settings dialog pop-up, select Do not import settings and click the OK button (this usually occurs when there is a previous installation of Android Studio):

Figure 0.1: The import settings dialog

Next, the Data Sharing dialog will pop up; click the Don't send button to disable sending anonymous usage data to Google:

Figure 0.2: The Data Sharing dialog

In the Welcome dialog, click the Next button to start the setup:

Figure 0.3: The Welcome dialog

In the Install Type dialog, select Standard to install the recommended settings. Then, click the Next button:

Figure 0.4: The Install Type dialog

In the Select UI Theme dialog, choose your preferred IDE theme—either Light or Dracula (dark theme) - then click the Next button:

Figure 0.5: The Select UI Theme dialog

In the Verify Settings dialog, review your settings and then click the Finish button. The setup wizard downloads and installs additional components, including the Android SDK:

Figure 0.6: The Verify Settings dialog

Once the download finishes, you can click the Finish button. You are now ready to create your Android project.

Installing the Code Bundle

You can download the code files and activity solutions from GitHub at https://github.com/PacktPublishing/How-to-Build-Android-Apps-with-Kotlin. Refer to these code files for the complete code bundle.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have any questions about this book, please mention the book title in the subject of your message and 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 could report this to us. Please visit www.packtpub.com/support/errata and complete the form.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you could 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 authors.packtpub.com.

Please leave a review

Let us know what you think by leaving a detailed, impartial review on Amazon. We appreciate all feedback – it helps us continue to make great products and help aspiring developers build their skills. Please spare a few minutes to give your thoughts – it makes a big difference to us.

1. Creating Your First App