How To Build Android Apps With Kotlin A Practical Guide To Developing Testing and Publishing Your First Android Apps 2nd Edition Alex Forrester
How To Build Android Apps With Kotlin A Practical Guide To Developing Testing and Publishing Your First Android Apps 2nd Edition Alex Forrester
com
https://textbookfull.com/product/android-continuous-integration-build-
deploy-test-automation-for-android-mobile-apps-pradeep-macharla/
textbookfull.com
https://textbookfull.com/product/brunch-planner-delicious-brunch-
recipes-everyone-should-know-2nd-edition-booksumo-press/
textbookfull.com
https://textbookfull.com/product/differential-calculus-for-jee-main-
and-advanced-3rd-edition-vinay-kumar/
textbookfull.com
https://textbookfull.com/product/changing-the-church-transformations-
of-christian-belief-practice-and-life-1st-edition-vladimir-latinovic/
textbookfull.com
https://textbookfull.com/product/transacting-as-art-design-and-
architecture-a-non-commercial-market-1st-edition-marsha-bradfield/
textbookfull.com
https://textbookfull.com/product/drunk-japan-law-and-alcohol-in-
japanese-society-1st-edition-mark-d-west/
textbookfull.com
Earth Frequency First Edition Melissa Alvarez
https://textbookfull.com/product/earth-frequency-first-edition-
melissa-alvarez/
textbookfull.com
How to Build Android Apps
with Kotlin
Second Edition
Alex Forrester
Eran Boudjnah
Alexandru Dumbravan
Jomar Tigcal
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.
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
– 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
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.
Table of Contents
Prefacexv
2
Building User Screen Flows 51
Technical requirements 51 Exercise 2.01 – logging the Activity
Callbacks55
The Activity lifecycle 52
viii Table of Contents
Saving and restoring the Activity Exercise 2.05 – retrieving a result from
state63 an Activity 84
Exercise 2.02 – saving and restoring the Intents, Tasks, and Launch
state in layouts 63
Modes95
Exercise 2.03 – saving and restoring the
Exercise 2.06 – setting the Launch Mode
state with Callbacks 71
of an Activity 96
Activity interaction with Intents 77 Activity 2.01 – creating a login form 101
Exercise 2.04 – an introduction to Intents 78
Summary102
3
Developing the UI with Fragments 103
Technical requirements 104 Exercise 3.02 – adding fragments statically to
an activity 117
The fragment lifecycle 104
onAttach105 Static fragments and dual-pane
onCreate106 layouts127
onCreateView106 Exercise 3.03 – dual-pane layouts with static
onViewCreated106 fragments128
onActivityCreated106
Dynamic fragments 145
onStart106
Exercise 3.04 – adding fragments dynamically
onResume106
to an activity 146
onPause107
onStop107 Jetpack Navigation 150
onDestroyView107 Exercise 3.05 – adding a Jetpack navigation
onDestroy107 graph151
onDetach107 Activity 3.01 – creating a quiz on the planets 156
Exercise 3.01 – adding a basic fragment and Summary160
the fragment lifecycle 108
4
Building App Navigation 161
Technical requirements 162 Exercise 4.01 – creating an App with a
navigation drawer 164
Navigation overview 162
Navigation drawer 162 Bottom navigation 181
Table of Contents ix
Exercise 4.02 – adding bottom navigation to Activity 4.01 – building primary and
your app 181 secondary app navigation 198
6
Adding and Interacting with RecyclerView 231
Technical requirements 232 Exercise 6.03 – responding to clicks 253
Adding RecyclerView to our Supporting different Item types 256
layout232 Exercise 6.04 – adding titles to
Exercise 6.01 – adding an empty RecyclerView260
RecyclerView to your main activity 233
Swiping to remove Items 266
Populating RecyclerView 235 Exercise 6.05 – adding swipe to delete
Exercise 6.02 – populating your functionality269
RecyclerView243
Adding items interactively 272
Responding to clicks in Exercise 6.06 – implementing an Add A Cat
RecyclerView251 button274
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
x Table of Contents
7
Android Permissions and Google Maps 281
Technical requirements 282 Map clicks and custom markers 299
Requesting permission from the Exercise 7.03 – adding a custom marker
user282 where the map was clicked 303
Exercise 7.01 – requesting the location Activity 7.01 – creating an app to find the
permission286 location of a parked car 308
8
Services, WorkManager, and Notifications 311
Technical requirements 312 Exercise 8.02 – tracking your SCA’s
work with a Foreground Service 326
Starting a background task using
WorkManager312 Activity 8.01 – reminder to
drink water 334
Exercise 8.01 – executing background work
with the WorkManager class 316 Summary335
Background operations noticeable to
the user – using a Foreground
Service321
9
Building User Interfaces Using Jetpack Compose 337
Technical requirements 337 Handling user actions 345
What is Jetpack Compose? 337 Exercise 9.02 – handling user inputs 347
Exercise 9.01 – first Compose screen 342 Theming in Compose 350
Table of Contents xi
Exercise 9.03 – applying themes 357 Activity 9.01 – first Compose app 366
Robolectric396 Summary438
Espresso401
11
Android Architecture Components 441
Technical requirements 442 Room463
Android components Entities464
background442 DAO467
ViewModel443 Setting up the database 469
Exercise 11.01 – shared ViewModel 445 Third-party frameworks 473
Exercise 11.03 – making a little room 475
Data streams 453 Activity 11.01 – a shopping notes app 480
LiveData454
Summary482
Additional data streams 461
xii Table of Contents
12
Persisting Data 483
Technical requirements 483 FileProvider499
Preferences and DataStore 484 The Storage Access Framework (SAF) 500
Asset files 500
SharedPreferences484
Exercise 12.03 – copying files 501
Exercise 12.01 – wrapping
SharedPreferences485 Scoped storage 508
DataStore489 Camera and media storage 509
Exercise 12.02 – Preference DataStore 491 Exercise 12.04 – taking photos 511
Files495 Activity 12.01 – dog downloader 518
Internal storage 496 Summary521
External storage 498
13
Dependency Injection with Dagger, Hilt, and Koin 523
Technical requirements 523 Scopes536
The necessity of dependency Subcomponents537
injection524 Exercise 13.02 – Dagger injection 538
15
Architecture Patterns 585
Technical requirements 586 Exercise 15.02 – using Repository with Room
in an Android project 595
Getting started with MVVM 586
Binding data on Android with data Using WorkManager 598
binding588 Exercise 15.03 – adding WorkManager to an
Exercise 15.01– using data binding in an Android Project 598
Android project 590 Activity 15.01 – revisiting the TV Guide app 601
Using Retrofit and Moshi 593 Summary603
Implementing the Repository pattern 593
16
Animations and Transitions with CoordinatorLayout
and MotionLayout 605
Technical requirements 606 Adding activity transitions through XML 606
Activity transitions 606 Adding activity transitions through code 607
xiv Table of Contents
17
Launching Your App on Google Play 639
Preparing your apps for release 640 Uploading an app to Google
Versioning apps 640 Play653
Creating a keystore 641 Creating a store listing 653
Exercise 17.01 – creating a keystore in Preparing the release 654
Android Studio 641 Rolling out a release 656
Storing the keystore and passwords 644
Managing app releases 657
Signing your apps for release 646
Release tracks 657
Exercise 17.02 – creating a signed APK 646
Staged rollouts 658
Android app bundle 649
Managed publishing 660
Exercise 17.03 – creating a signed app bundle 650
Activity 17.01 – publishing an app 662
App signing by Google Play 652
Index665
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 the 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, Adding and Interacting with 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, Building User Interfaces Using Jetpack Compose, shows how Jetpack Compose works, how
to apply styles and themes, and how to use Jetpack Compose in projects started with layout files.
Chapter 10, 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 11, Android Architecture Components, provides an insight into components from the Android
Jetpack libraries, such as ViewModel, which will help separate the business logic from the user interface
code. We will then look at how we can use observable data streams such as LiveData to deliver data
to the user interface. Finally, we will look at the Room library to analyze how we can persist data.
Chapter 12, 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 13, Dependency Injection with Dagger, Hilt, and Koin, explains the concept of dependency
injection and the benefits it provides to an application. Frameworks such as Dagger, Hilt, and Koin
are introduced to help you manage your dependencies.
Preface xvii
Chapter 14, Coroutines and Flow, introduces you to doing background operations and data manipulations
with coroutines and Flow. You’ll also learn about manipulating and displaying data using Flow operators
and LiveData transformation.
Chapter 15, 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 16, Animations and Transitions with CoordinatorLayout and MotionLayout, discusses how to
enhance your apps with animations and transitions with CoordinatorLayout and MotionLayout.
Chapter 17, 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,
and finally launching your app.
Software requirements
You’ll also need the following software installed in advance:
unpack the ZIP file into your preferred location. Open your Terminal and navigate to the android-
studio/bin/ directory and execute studio.sh.
Next, the Data Sharing dialog will pop up; click either the Send usage statistics to Google button or
the Don’t send button to disable sending anonymous usage data to Google:
In the Welcome dialog, click the Next button to start the setup:
In the Install Type dialog, select Standard to install the recommended settings. Then, click the
Next button:
In the Select UI Theme dialog, choose your preferred IDE theme—either Light or Darcula (dark
theme)—then click the Next button:
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:
Preface xxi
Once the download finishes, you can click the Finish button. You are now ready to create your
Android project.
If you are using the digital version of this book, we advise you to type the code yourself or access
the code from the book’s GitHub repository (a link is available in the next section). Doing so will
help you avoid any potential errors related to the copying and pasting of code.
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “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>
When we wish to draw your attention to a particular part of a code block, the relevant lines or items
are set in bold:
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words
in menus or dialog boxes appear in bold. Here is an example: “Click Finish and your virtual device
will be created.”
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at customercare@
packtpub.com and mention the book title in the subject of your message.
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 www.packtpub.com/support/errata and fill in 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 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 authors.packtpub.com.
https://packt.link/free-ebook/9781837634934
Language: Hungarian
A KI ÖRÖKKÉ BUJDOSOTT
ÉS EGYÉB ELBESZÉLÉSEK
A KI ÖRÖKKÉ BUJDOSOTT
ÉS EGYÉB ELBESZÉLÉSEK
BUDAPEST MDCCCCI
VIII., ÜLLŐI-ÚT 18. SZÁM.
RÉVAI TESTVÉREK
IRODALMI INTÉZET R.-T.
Eötvös Károly
A KI ÖRÖKKÉ BUJDOSOTT
ÉS EGYÉB ELBESZÉLÉSEK
BUDAPEST MDCCCCI
VIII., ÜLLŐI-ÚT 18. SZÁM.
RÉVAI TESTVÉREK
IRODALMI INTÉZET R.-T.