(This page has no text content)
Kotlin and Android Development featuring Jetpack Build Better, Safer Android Apps by Michael Fazio Version: P1.0 (June 2021)
Copyright © 2021 The Pragmatic Programmers, LLC. This book is licensed to the individual who purchased it. We don’t copy-protect it because that would limit your ability to use it for your own purposes. Please don’t break this trust—you can use this across all of your devices but please do not share this copy with other members of your team, with friends, or via file sharing services. Thanks. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. About the Pragmatic Bookshelf The Pragmatic Bookshelf is an agile publishing company. We’re here because we want to improve the lives of developers. We do this by creating timely, practical titles, written by programmers for programmers. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://pragprog.com. Our ebooks do not contain any Digital Restrictions Management, and have always been DRM-free. We pioneered the beta book concept, where you can purchase and read a book while it’s still being written, and provide feedback to the author to help make a better book for everyone. Free resources for all purchasers include source code downloads (if applicable), errata and discussion forums, all available on the book’s home page at pragprog.com. We’re here to make your life easier. New Book Announcements Want to keep up on our latest titles and announcements, and occasional special offers? Just create an account on pragprog.com (an email address and a password is all it takes) and select the checkbox to receive newsletters. You can also follow us on twitter as @pragprog. About Ebook Formats If you buy directly from pragprog.com, you get ebooks in all available formats for one price. You can synch your ebooks amongst all your devices (including iPhone/iPad, Android, laptops, etc.) via Dropbox. You get free updates for the life of the edition. And, of course, you can always come back and re-download your books when needed. Ebooks bought from the Amazon Kindle store are subject to Amazon’s polices. Limitations in Amazon’s file format may cause ebooks to display differently on different devices. For more information, please see our FAQ at pragprog.com/#about- ebooks. To learn more about this book and access the free resources, go to https://pragprog.com/book/mfjetpack, the book’s homepage. Thanks for your continued support, Andy Hunt The Pragmatic Programmers The team that produced this book includes: Dave Rankin (CEO), Janet Furlow (COO), Tammy Coron (Managing Editor), Michael Swaine (Development Editor), Sakhi MacMillan (Copy Editor), Potomac Indexing, LLC (Indexing), Gilson Graphics (Layout), Andy Hunt and Dave Thomas (Founders) For customer support, please contact support@pragprog.com. For international rights, please contact rights@pragprog.com.
Table of Contents Acknowledgments Preface Introduction Who Is This Book For If You’re New to Android and/or Kotlin How to Read This Book Development Tips for the Book Online Resources Ready to Go? Part I. Penny Drop 1. Initialize the Penny Drop App How to Play Penny Drop Create the App What Else Do We Need? Summary and Next Steps 2. Build Views with Fragments Build a Fragment (Pick Players) Add Data Binding to the App Build Another Fragment (Game) Summary and Next Steps
3. Bind Data with ViewModels Create a ViewModel (Pick Players) Bind ViewModel to a Fragment (Pick Players) Add AI Spinner to Player List Items Customize the Player List Items Create Another ViewModel (Game) Bind ViewModel to a Fragment (Game) Summary and Next Steps 4. Update LiveData with Conditional Game Logic Create GameHandler Start a Game More GameViewModel Functions: roll() and pass() Update the UI Create Turn Summary Text Handle AI Turns with Coroutines and First-Class Functions Summary and Next Steps 5. Persist Game Data with Room Add Room to the App Add a RoomDatabase Class Create a DAO Class Add Entity Classes Add Data During Database Creation Add Converters to the Database Create a Repository Class Access the Database from a ViewModel Update the UI Data Binding Summary and Next Steps
6. Build a List with RecyclerView Add the RecyclerView Build the List Item Layout Create a Custom ListAdapter Connect Adapter to RecyclerView Load Data into RecyclerView from Database Summary and Next Steps 7. Customize an App with Settings and Themes Add a New SettingsFragment Use Saved Preferences Add Themes Change Themes Add Night Mode Support Add an About the App Section Summary and Next Steps Part II. Android Baseball League 8. Initialize the Android Baseball League App Welcome to the Official ABL App Create the App Configure the Activity Add the First Fragment Summary and Next Steps 9. Navigate via Navigation Drawer Add the Navigation Drawer Add Fragments (Standings and Single Team)
Pass Data with Safe Args Navigate Directly via a Deep Link Summary and Next Steps 10. Load and Save Data with Coroutines and Room Create a Database Work with Retrofit Load Data from External APIs Add a New Fragment (Scoreboard) Summary and Next Steps 11. Display Data with Paging Add Two New Fragments (Leaders and Single Player) Add a New Fragment (Players) Handle Paging Data in the App Display Paging Data in a RecyclerView List Summary and Next Steps 12. Personalize the Android Baseball League App Build a Settings Screen via Code Extract Colors with Palette Add and Group Additional Preferences Reliably Complete Background Work with WorkManager Summary and Next Steps 13. Send Info to and from the Android Baseball League App Alert Users with Notifications Send Cloud-Based Alerts with Push Notifications Share Links with Android Sharesheet
Summary and Next Steps Part III. Test Your App 14. Unit Test Your App with JUnit Add Unit Tests Test a ViewModel Class Test a Data Access Object (DAO) Summary and Next Steps 15. Test Your App’s UI with Espresso Add UI Tests Add More UI Tests Summary and Next Steps Part IV. Appendixes A1. Install Android Studio Download Android Studio Install Android Studio Set Up an Android Virtual Device (AVD) A2. Troubleshooting Your App Debug Your App Display Messages with the Toast Class Log Messages to Logcat Wrapping Up A3. Gradle Dependencies
Classpath Dependencies Implementation Dependencies KAPT Dependencies Test Dependencies Copyright © 2021, The Pragmatic Bookshelf.
Early Praise for Kotlin and Android Development featuring Jetpack Learning a new language and platform at the same time can seem daunting, but this book makes it both fun and easily understandable. The sample apps make complex topics such as view binding and unit testing relatable and easy to understand. → Markus Neuhoff Android/Kotlin Course Author, Pluralsight Michael does an excellent job explaining Kotlin, from the basics to the most advanced topics. The two example applications are incredibly helpful for both beginners and advanced developers. Coming from a different background in mobile development, having the step-by-step on the basics on how to use Android Studio and following the examples in the book made it easy to focus on the important topic, which is learning Kotlin. → Pablo Siller Mobile Lead, Trek Bicycle If you’re serious about developing Android applications with Kotlin, you’ve found a thorough and yet an approachable book that will guide you through every step of developing and testing. → Dr. Venkat Subramaniam Founder, Agile Developer, Inc. A great walkthrough of using Kotlin for Android development. Plenty of code examples and a clear trajectory from beginner to advanced.
→ Greg Levenhagen Principal Consultant, MS Regional Director, MS AI MVP, Skyline Technologies, Inc. Whether you’re new to or have experience with Kotlin, this book is a valuable resource. With great project-based examples, you’ll easily be able to adapt what you learn to your own projects. This is a must-have for any developer’s collection. → Rolando Lopez Senior Mobile Applications Developer, Milwaukee Tool As someone that has no Android-development experience, but a strong software development background, I found this to be a very engaging and informative first step into the world of Android. Highly recommended for anyone looking to get into this world! → Brandon Martinez Senior Service Engineer, Microsoft
Acknowledgments First off, a big thank you to the entire Pragmatic Bookshelf team, and especially three particular people. I want to express a great deal of gratitude to my editor, Michael Swaine, for taking this journey with me, supporting me at each step of the process, and sometimes just giving me the “You’re all good, don’t worry” that really I needed. This book would never have been a possibility without Brian MacDonald coming up to me at THAT Conference and saying “Hey, do you want to write a book on Kotlin?”, then working with me through the entire pre-book process. And finally Brian Hogan, who assured me that PragProg was great (turns out they are) and that I could actually do this book (turns out I could). My sincere appreciation to my tech reviewers: Joe Vetta, Rolando Lopez, Ben Gavin, Brandon Martinez, and Andrew Petersen. The fact that you all took the time to read through my book and help make it better means so much to me, and I’m eternally grateful for that. Also, thank you to Keno Basedow for finding a number of ways I could improve the book and make it clearer during the beta process. I’ve been lucky enough to have support from everyone around me. This includes the whole Skyline crew, who have been great with this crazy side project of mine. Craig and Joe, for tolerating my incessant “OMG KOTLIN” comments the past few years. Rolando, for being as excited as anyone when I found out the book was happening. And all my friends and
[1] family who knowingly (or unknowingly) are part of the book in the Android Baseball League. As I’m definitely no artist, I needed some help with the icons and logos in the book. Many of them are right from Google’s Material Design library, which can be found inside Android Studio, but I did grab a number from a few sites. The full list can be found in the source code under images/image-rights.txt, but here’s the quick summary: most of the team logos and icons were from http://www.flaticon.com, made by Freepik, Good Ware, Smashicons, smalllikeart, and Vitaly Gorbachev. The Skyline logo is from Skyline Technologies, my company when writing this book, and the People’s Flag of Milwaukee[1] is used as the Milwaukee Sunrise logo. The scoreboard icon from the ABL app as well as both the dice and coin icons from Penny Drop are from http://www.materialdesignicons.com. And finally, to my family, I love you all so much: Mom and Dad, thank you for always being there for me and doing everything possible to help me succeed. Your constant love and support has made me who I am today and is the example I follow now as a father. Hazel, you’re the coolest kiddo, and I love getting to be your dad. I’m so very proud of you, and hearing you say that you’re proud of me for the book means the world to me. Emily, thank you for holding down things while I’ve been getting the book done and everything that went with it. There’s no way I could have accomplished this without you saying “You do whatever you need to, I’ve got everything else covered.” There’s so much more I could say, but I’ll just leave it at—you’re the best. Footnotes https://milwaukeeflag.com/ Copyright © 2021, The Pragmatic Bookshelf.
Preface With Kotlin and Jetpack, Android development is now smoother and more enjoyable than ever before. In this book, we’re going to dive right into Android development by writing two complete Android apps. With the first app, Penny Drop, you will create a full game complete with random die rolls, customizable rules, and AI opponents. You’ll build lightweight Fragment views with data binding, quickly and safely update data with ViewModel classes, and handle all app navigation in a single location. You’ll be guided to use Kotlin with Android-specific Kotlin extensions to efficiently write null-safe code without all the normal boilerplate required for pre-Jetpack + Kotlin apps. You’ll see how to persist and retrieve data as full objects with the Room library, then display that data with ViewModels and list records in a RecyclerView. Next, you’ll create the official app for the Android Baseball League. It’s a fake league but a real app, where you use what you learn with Penny Drop and build up from there. You’ll navigate all over the app via a navigation drawer, including specific locations via Android App Links. You’ll handle asynchronous and web service calls with Kotlin coroutines, display that data smoothly with the Paging library, and send notifications to a user’s phone from your app. Ready? Let’s build some Android apps! Copyright © 2021, The Pragmatic Bookshelf.
Introduction Welcome to modern Android development! I know I’ve already thrown the phrase “modern” out a few times, but it’s accurate. Kotlin makes the entire Android dev experience so much nicer than it was in the past, and then you add in the Jetpack frameworks and concepts? The whole situation gets better and better. When we first discussed creating this book, I knew I wanted a way to share my love of Kotlin with others but wasn’t sure what I wanted for a topic. Android was always the most logical spot because I’ve worked with Android for years, but I felt like there were already so many Android books out there. How would my book be any different? Attempting to make the book unique led me to two conclusions: I wanted to focus on the newest approaches/libraries possible, and I wanted to make the apps interesting. The former was handled by squaring in on Jetpack. This is Google’s recommended approach for Android dev, and they’ve done such a good job of introducing better ways to handle standard actions within an Android app. It may not seem as revelatory if you’re new to Android development, but as someone who’s done this for years, trust me that the Jetpack libraries make your life so much easier. The second piece here is the apps. While there’s nothing wrong with starting with a “To-Do List” app, I wanted something more fun. Building your first Android app and it’s a game? That’s way better! I love how Penny Drop is a nice,
simple table game, so we can instead focus on everything else we need to do to build the app. Plus, once we get the core game running, we have a bunch of ways to add on additional features while highlighting useful parts of Android development. Then there’s the Android Baseball League. This is in a lot of ways my personal baseball fandom coming out, but it also gives us a sample app that looks like something you’d see in the Play Store. Plus, we end up with a number of ways to pull data into the app from APIs, which is basically a requirement for Android apps nowadays. Actually, the APIs are probably the best example of my love of baseball. All the data for the Android Baseball League was created and/or generated by me. This includes the teams, players, box scores, all of it. As a developer, two of the things I’ve wanted to do most in my life were to write a book and create a baseball simulator, and I was able to do both at once. I so enjoy how great Penny Drop works as an app, but the ABL app is the most near and dear to my heart. I first and foremost included ABL because it’s an excellent advanced app, but man, was it ever fun to put together. I love Kotlin, I love Android, and I love having this chance to share both with you. I hope you feel the same way once you’ve gone though the book and that you can sense my excitement the entire way.
Who Is This Book For This book is intended both for new developers and anyone experienced with Android and/or Kotlin. I try to explain what’s going on for new devs but also give a heads-up when something may be review for Android pros. My intent is that all skill levels can benefit in one way or another from the apps we build. We tested this out during the review process, where developers of varying skill levels went through the book and all of them said they learned new things. Even the most senior professional Android developer that went through the book sent me multiple messages about all the new things he was learning, so I’m optimistic you’ll get a bunch out of this book no matter where you are with Android or Kotlin.
If You’re New to Android and/or Kotlin This may seem overwhelming at first, but as the book goes on, things will make more and more sense. I recommend checking out the source code I’ll mention in the next section to see how things fit together. With Android apps, a high-level overview is that your UI (what the user sees) is mostly handled within XML, while the logic is handled with the Kotlin code. Speaking of Kotlin, you’ll find a number of mentions to Java in the book. Now, we are not going to be writing any Java code in the book, but we will be interacting with it, as most Android libraries were written in Java. Therefore, our Kotlin setup includes associating with a Java version, and we even use a directory called java for our Kotlin code. This is all because both Java and Kotlin compile down to the same byte code, so we can use them interchangeably. Just try to not be thrown off when you see Java mentioned, because it doesn’t mean you need to start writing Java code or anything.
How to Read This Book As I mentioned above, the book is split into two apps: Penny Drop and Android Baseball League. Penny Drop is intended as a introduction to Android, Jetpack, and Kotlin. If you’re new to any of those, it’ll definitely be worth your time to build the Penny Drop app (plus, it’s fun). But even for those of you who know Android well, I bet you’ll learn a few things as well in going through the first app. The ABL app is where things get more advanced. Many of the chapters are effectively part two of ones from Penny Drop. For example, Chapter 5, Persist Game Data with Room, is the introduction to using Room, Android’s ORM (object-relational mapping) library, which makes for easier database interaction. Then, Chapter 10, Load and Save Data with Coroutines and Room, takes those database concepts and adds in API calls and more coroutines. As a result, while building Penny Drop first isn’t a requirement, it does make things clearer. I go through things faster with the ABL app, and there’s more pre-existing code for you to integrate instead of building everything yourself. Speaking of which, all the source code for the book can be found at https://media.pragprog.com/titles/mfjetpack/code/mfjetpack- code.zip. I included the end result from each chapter of the book so you always have both a reference and a starting point for the next chapter as needed. Also, with the ABL app, there’s code to copy from that ZIP file into your project. The intent here is to get a more full-featured app without you having to write every bit of code but instead letting you focus on the main concepts of the chapter. The last two main chapters of the book are focused on testing, in particular unit and Android UI testing. Those both use the
Penny Drop app as the basis. If you didn’t want to build Penny Drop but instead just want to try out the testing pieces, you can always grab code from the ZIP to use as your baseline when getting everything set. You’ll also find three appendixes at the end of the book: one with instructions for installing Android Studio, one with troubleshooting tips for development, and one with all the dependencies used in the book. The key feature of the last appendix is that all the dependency version numbers can be found there. I went that route instead of mentioning them in each chapter to avoid inconsistencies, plus then we have a single spot to check for any dependency. Finally, a heads-up that while the book was written (mostly) on Windows and the screenshots are all of the Windows version of Android Studio, things will work the same if you’re using a Mac. This means you’re free to develop on the OS you’re most comfortable using.
Comments 0
Loading comments...
Reply to Comment
Edit Comment