How to Build Android Apps with Kotlin, 2nd Edition (Alex Forrester, Eran Boudjnah etc.)(Z-Library)
, , ,
Programming Language
A practical guide to developing, testing, and publishing your first Android apps
8
Views
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
BIRMINGHAM—MUMBAI How to Build Android Apps with Kotlin Second Edition Copyright © 2023 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 authors, 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. Group Product Manager: Rohit Rajkumar Publishing Product Manager: Nitin Nainani Content Development Editor: Abhishek Jadhav Technical Editor: Simran Ali Copy Editor: Safis Editing Project Coordinator: Aishwarya Mohan Proofreader: Safis Editing Indexer: Manju Arasan Production Designer: Joshua Misquitta
Page
3
Marketing Coordinator: Nivedita Pandey First published: February 2021 Second edition: May 2023 Production reference: 1210423 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-83763-493-4 www.packtpub.com Dedicated to my wife Angela and daughter Catherine for all their love and support. – Alex Forrester To my endlessly supportive wife, Lea, for always being there for support. To my parents, Amos and Tirtsa, for spending some of their best years teaching and encouraging me. I could not have asked for better people in my life, so thank you all. – Eran Boudjnah Dedicated to Niki for her constant support. – Alexandru Dumbravan To my loving wife, Celine, for her support and encouragement. To my parents for all their sacrifices and for raising me well. – Jomar Tigcal Contributors About the authors Alex Forrester is an experienced software developer with more than 20 years of experience in mobile and web development and content management systems. He has worked with Android since 2010, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The
Page
4
Automobile Association, HSBC, 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 worked with Android since 2011, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat and Plume Design) to large-scale companies (Sky and HSBC) 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 Brentwood, England, with Lea, his wife. Alexandru Dumbravan is an Android developer with more than 10 years of experience building Android apps, focusing on fintech applications since 2016 when he moved to London. In his spare time, Alex enjoys video games, movies, and the occasional gym visit. Jomar Tigcal is an Android developer with over 14 years of experience in mobile and software development. He has worked on various stages of Android app development for small start-ups and large companies since 2012. 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, BC, Canada, with his wife Celine. About the reviewers Ed Holloway-George is an Android developer and Google Developer Expert originally from Oxford, England, but currently living in Nottingham. An Android developer for just over 10 years, Ed now works for ASOS as a lead developer having previously worked on well-known applications such as National Trust, My Oxfam, Snoop, Carling Tap, and more. In his spare time, Ed can be found speaking at conferences, writing blog posts, and sharing pictures of his dog. Guruprasad Bagade is a senior developer who has led teams and has over a decade of experience in mobile and software development. He has witnessed changes in Android development from Java to Kotlin with the most recent framework libraries. He primarily worked in the banking domain for Barclays and JP Morgan clients. He has hired everyone from freshers to experienced developers for organizations and helped set up teams while also publishing knowledge articles on Android on the internal portals of the various organizations where he has worked. He has published technical research papers at the Institute of Electrical and Electronics Engineers (IEEE) and international and national conferences. He also contributes to open source projects. In his spare time, he keeps himself up to date with the latest technologies.
Page
5
Table of Contents Preface
Page
6
Part 1: Android Foundation 1 Creating Your First App Technical requirements 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 The project-level build.gradle file The app-level build.gradle file 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
Page
7
Building User Screen Flows Technical requirements 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 Technical requirements The fragment lifecycle onAttach onCreate onCreateView onViewCreated onActivityCreated onStart onResume onPause onStop
Page
8
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 Technical requirements 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
Page
9
Part 2: Displaying Network Calls 5 Essential Libraries: Retrofit, Moshi, and Glide Technical requirements Introducing REST, API, JSON, and XML 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 Adding and Interacting with RecyclerView Technical requirements Adding RecyclerView to our layout Exercise 6.01 – adding an empty RecyclerView to your main activity Populating RecyclerView Exercise 6.02 – populating your RecyclerView Responding to clicks in RecyclerView Exercise 6.03 – responding to clicks Supporting different Item types
Page
10
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 Technical requirements Requesting permission 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 Technical requirements Starting a background task using WorkManager Exercise 8.01 – executing background work with the WorkManager class
Page
11
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 Building User Interfaces Using Jetpack Compose Technical requirements What is Jetpack Compose? Exercise 9.01 – first Compose screen Handling user actions Exercise 9.02 – handling user inputs Theming in Compose Exercise 9.03 – applying themes Adding Compose to existing projects Activity 9.01 – first Compose app Summary
Page
12
Part 3: Testing and Code Structure 10 Unit Tests and Integration Tests with JUnit, Mockito, and Espresso Technical requirements Types of testing JUnit Android Studio testing tips Mockito Exercise 10.01 – testing the sum of numbers Integration tests Robolectric Espresso Exercise 10.02 – double integration UI tests Testing in Jetpack Compose Exercise 10.03 – random waiting times TDD Exercise 10.04 – using TDD to calculate the sum of numbers Activity 10.01 – developing with TDD Summary 11 Android Architecture Components Technical requirements
Page
13
Android components background ViewModel Exercise 11.01 – shared ViewModel Data streams LiveData Additional data streams Room Entities DAO Setting up the database Third-party frameworks Exercise 11.03 – making a little room Activity 11.01 – a shopping notes app Summary 12 Persisting Data Technical requirements Preferences and DataStore SharedPreferences Exercise 12.01 – wrapping SharedPreferences DataStore Exercise 12.02 – Preference DataStore Files Internal storage External storage FileProvider The Storage Access Framework (SAF)
Page
14
Asset files Exercise 12.03 – copying files Scoped storage Camera and media storage Exercise 12.04 – taking photos Activity 12.01 – dog downloader Summary 13 Dependency Injection with Dagger, Hilt, and Koin Technical requirements The necessity of dependency injection Manual DI Exercise 13.01 – manual injection Dagger 2 Consumers Providers Connectors Qualifiers Scopes Subcomponents Exercise 13.02 – Dagger injection Hilt Exercise 13.03 – Hilt injection Koin Exercise 13.04 – Koin injection Activity 13.01 – injected repositories Summary
Page
15
Part 4: Polishing and Publishing an App 14 Coroutines and Flow Technical requirements Using Coroutines on Android Creating coroutines Adding coroutines to your project Exercise 14.01 – using coroutines in an Android app Transforming LiveData Exercise 14.02 – LiveData transformations Using Flow on Android Collecting Flows on Android Creating Flows with Flow Builders Using operators with Flows Exercise 14.03 – using Flow in an Android application Activity 14.01 – creating a TV Guide app Summary 15 Architecture Patterns Technical requirements Getting started with MVVM Binding data on Android with data binding Exercise 15.01– using data binding in an Android project Using Retrofit and Moshi
Page
16
Implementing the Repository pattern Exercise 15.02 – using Repository with Room in an Android project Using WorkManager Exercise 15.03 – adding WorkManager to an Android Project Activity 15.01 – revisiting the TV Guide app Summary 16 Animations and Transitions with CoordinatorLayout and MotionLayout Technical requirements Activity transitions Adding activity transitions through XML Adding activity transitions through code Starting an activity with an activity transition Exercise 16.01 – creating activity transitions in an app Adding a shared element transition Starting an activity with the shared element transition Exercise 16.02 – creating the shared element transition Animations with CoordinatorLayout Animations with MotionLayout Adding MotionLayout Creating animations with MotionLayout Exercise 16.03 – adding animations with MotionLayout The Motion Editor Debugging MotionLayout Modifying the MotionLayout path
Page
17
Exercise 16.04 – modifying the animation path with keyframes Activity 16.01 – Password Generator Summary 17 Launching Your App on Google Play Preparing your apps for release Versioning apps Creating a keystore Exercise 17.01 – creating a keystore in Android Studio Storing the keystore and passwords Signing your apps for release Exercise 17.02 – creating a signed APK Android app bundle Exercise 17.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 Preparing the release Rolling out a release Managing app releases Release tracks Staged rollouts Managed publishing Activity 17.01 – publishing an app Summary
Page
18
Index Other Books You May Enjoy
Page
19
Preface 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 Kotlin programming language for app development. Then, you’ll learn how to create apps and run them on virtual devices using guided exercises. You’ll cover the fundamentals of Android development, from structuring an app to building out the UI with activities, 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. Next, you’ll build user interfaces using Jetpack Compose. Moving on, you’ll get to grips with testing, covering the full spectrum of the test pyramid. You’ll also learn how Android Architecture Components (AAC) is used to cleanly structure your code and explore various architecture patterns and the benefits of dependency injection. Coroutines and the Flow API 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. Toward 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.
Page
20
Who this book is for 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.
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A hands-on, exercise-driven path from your first Android Studio project to tested, well-structured, publishable Kotlin apps. Best for developers with basic Kotlin who want practical Android skills rather than theory.
【Book Arc】
- **Opening (~0%–10%)**: Sets up Android Studio, project configuration, the manifest, and Material theming — the groundwork that makes every later exercise runnable.
- **Early (~10%–32%)**: Builds UI fundamentals — layouts, input fields, intents for navigation, and the fragment lifecycle — solving the "how do screens and data connect" problem.
- **Middle (~32%–48%)**: Moves into adaptive and navigational structure: dual-pane layouts for tablets, the Jetpack Navigation component, and navigation patterns like the drawer.
- **Late (~48%–70%)**: The excerpts jump to Part 3, covering testing (JUnit, Mockito, Robolectric, Espresso, Compose testing, TDD) and Android Architecture Components — the shift from "it works" to "it's verifiable and maintainable."
- **Ending (~70%–100%)**: Excerpts do not cover this range; presumably publishing and release topics, but this guide cannot confirm their content.
【Key Takeaways】
- **Configuration choices shape the whole project** (Opening): package naming, minimum SDK, and save location are decided at project creation and are awkward to change later, so the book treats them as real decisions, not defaults to click through.
- **The manifest is the app's contract with the system** (Early): the MAIN action plus LAUNCHER category is what makes an app launchable; removing either breaks startup in specific, instructive ways.
- **Material components add polish cheaply** (Early): wrapping EditText in TextInputLayout/TextInputEditText gives labels, hints, and focus animation with minimal code — a recurring theme of using ready-made components over custom views.
- **Fragments have their own lifecycle nested inside the activity's** (Early): callbacks fire child-first on teardown, and view work belongs in onViewCreated, not onCreateView — a distinction the book demonstrates via logging and rotation.
- **One codebase, two layouts** (Middle): resource qualifiers like sw600dp let phones show list-then-detail while tablets show a dual-pane view, with the activity deciding behavior by checking whether the detail view exists.
- **Navigation is about context, not just movement** (Middle): the book frames drawer, top-level, and secondary destinations around always telling users where they are, with the Navigation component encoding flows as graphs.
- **Testing is layered, not monolithic** (Late): unit tests with JUnit and Mockito, integration tests with Robolectric, and UI tests with Espresso and Compose testing each cover a different confidence level.
- **TDD is taught as a workflow, not a slogan** (Late): exercises walk from a failing test to implementation, including an activity-scale TDD exercise, making the discipline concrete.
【Reading Tips】
- **Do the exercises in order through the early chapters.** The book is exercise-first; reading without typing leaves the manifest, lifecycle, and layout lessons abstract.
- **Deep-read the fragment lifecycle and navigation chapters.** These are the densest conceptual spots; the callback ordering and dual-pane logic reward slow reading and logcat experimentation.
- **Skim the theming and XML styling sections** if you already know Material Design — treat them as reference for color roles (primary, variant, on-primary) rather than linear reading.
- **Treat Part 3 as a separate pass.** Testing and architecture components assume the UI chapters are solid; return to them after building at least one small app end to end.
- **Keep Android Studio open beside the book.** Version-specific dialogs and defaults drift, so match the text against your actual IDE.
【Coverage Limits】
The excerpts are heavily weighted toward the opening, UI, fragments, navigation, and testing chapters; the later portion of the book (likely publishing and advanced topics) is not represented, so this guide cannot describe it.
Passage locations
Excerpt 1
keep the default or edit it to something different (such as Users/MyUser/android/projects). The default location will vary with the operating system you are...
View in text
Excerpt 2
ring name="welcome_to_the_app">Welcome to the app</string> <string name="please_enter_a_name">Please enter a full name!</string> 3. Next, we will update our...
View in text
Excerpt 3
iew, savedInstanceState: Bundle?): This callback is the one in between your fragment being fully created and being visible to the user. It’s where you’ll typ...
View in text
Excerpt 4
is unfamiliar, it is quite straightforward to understand: 1. ListFragment and DetailFragment are present as they would be if you were adding static fragments...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay