Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
100%
(1)
100% found this document useful (1 vote)
2K views
Murach Android Programming
Libro programacion en Android Author: Joel Murach
Uploaded by
Angie Becerril
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Murach Android Programming For Later
Download
Save
Save Murach Android Programming For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
100%
(1)
100% found this document useful (1 vote)
2K views
Murach Android Programming
Libro programacion en Android Author: Joel Murach
Uploaded by
Angie Becerril
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Murach Android Programming For Later
Carousel Previous
Carousel Next
Save
Save Murach Android Programming For Later
100%
100% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 720
Search
Fullscreen
TRAINING & REFERENCE murach’s Android programming Joel Murach Mike Muracu & Associates, INc. 4340 N. Knoll Ave. « Fresno, CA 93722 ‘www.murach.com + murachbooks @murach.comAuthor: Editor: Ray Halliday Android Consultant: Leo Landau Joel Murach Production Editor: Ben Murach Production: Maria Spera Books for Java programmers Murach’s Java Programming Murach’s Java Servlets and JSP Murach’s Oracle SQL and PL/SQL Books for Web developers Murach’s HTMLS and C883 Murach’s JavaScript and jQuery Murach’s JavaScript and DOM Scripting Murach’s PHP and MySQL Murach’s MySQL Books for .NET programmers Murach’s C# 2012 Murach’s ASP.NET 4.5 Web Programming with C# 2012 Murach’s Visual Basic 2012 Murach's ASP.NET 4.5 Web Programming with VB 2012 Murach’s SOL Server 2012 for Developers Books for IBM mainframe programmers Murach’s OS/390 and z/OS JCL Murach’s Mainframe COBOL 'S for the COBOL Programmer Murach's For more on Murach books, please visit us at www.murach.com © 2013, Mike Murach & Associates, Ine All rights reserved Printed in the United States of America 10987654321 ISBN: 978-1-890774-71-4Contents Introduction Section 1 Get started fast with Android Chapter 1 An introduction to Android Chapter 2 How to use Eclipse for Android development Chapter 3 How to develop your first Android app Chapter 4 How to test and debug an Android app Section 2 Essential Android skills Chapter 5 How to work with layouts and widgets Chapter 6 How to handle events Chapter 7 How to work with themes and styles Chapter 8 How to work with menus and preferences Chapter 9 How to work with fragments Section 3. The News Reader app Chapter 10 How to work with threads, files, adapters, and intents Chapter 11 How to work with services and notifications Chapter 12. How to work with broadcast receivers Section 4 The Task List app Chapter 13 How to work with SQLite databases Chapter 14. How to work with tabs and custom adapters Chapter 18 How to work with content providers Chapter 16 How to work with app widgets Section 5 Advanced Andr: skills Chapter 17 How to deploy an app Chapter 18 How to work with locations and maps, Appendixes Appendix A How to set up your PC for this book Appendix B_ How to set up your Mac for this book Appendix J How to use IntelliJ with this book xiii 33 n 121 151 193 225 249 283 369 587 579 641 661 681Expanded contents Expanded contents Section 1 Get started fast with Androi Chapter 1 An introduction to Andr Android overview ‘Types of devices ‘Types of apps Abriet history System archivectare How apps are compiled and run A simple Android app.. The user interface ‘The XML for the user intervace, 18 ‘The XML for the display text 2 ‘The Java source code 24 ‘The Android manifest 28 Chapter 2 How to use Eclipse for Android development How to work with existing projects. ‘An introduetion to Eclipse projects How to set the workspace How to importa project into the workspace. How to remove a project from the workspace How to work witi the user interface How to work with other XML resources How to work with the Java code How to set the run configuration How to run an app on a physical device How to run an app on an emulator How to work with a new project How to create anew project. How to work with the starting code. iow to use the code completion feature How to detect and correct errors and warnings o The Tester app.. ‘The user interface ‘The XML for the user interface 66 ‘The Java source code 66, Chapter 3 How to develop your first Android app How to develop the user interface .. The Tip Calculator app How to work with a layout. How to add widgets to a layout How to set the display text How to work with the strings xml file How to set properties Common properties ‘The XML for the usee interface. vvi Expanded contents Chapter 4 Section 2 Chapter 5 How to work with an activity, 92 How to get references to widgets 34 How to handle the EditorAction event. 96 How to get and set the text for widgets, Joo How to handle the Click event 102 The lifecycle of an activity 104 How to save and restore values 106 How to use the documentation for the Android APT, Los ‘The Java code for the app 110 How to test and debug an Android app Basic skills for testing and debugging ‘Typical test phases 122 How to check the layout. 124 The three types of errors 126 How to handle runtime errors 126 How to trace code execution. 128 How to use LogCat logging 128 How to use toasts 10 How to use the debugger. 132 How to set and remove breakpoints 132 How to step through code 14 How to inspect variables 134 How to inspect the stack trave 4 How to configure step filters, 136 How to configure your emulators. How to add an emulator for an old phone. 138 How to work with an emulator for an ald phone 142 How to add an emulator for a tablet. 144 Essential Android skills How to work h layouts and widgets An introduction to layouts and widgets... 152 ‘A summary of layouts 182 A summary of widgets 152 The View hierarchy 154 How to work with layouts. low to use a linear layout 156 How to use a table layout 160 How to use a frame layout 162 How to nest layouts 164 How to provide a landscape layout. 166 How to work with widgets How to use editable text views, 168 How to use check boxes. 172 How to use radio buttons 14 How to use spinners. 176 How to use seek bars. 180 How to display images 182 How to show and hide widgets 184 How to add seroll bars 186Chapter 6 Chapter 7 Chapter 8 Expanded contents How to handle events A summary of li High-level events Low-level evens. Four techniques for handling events. How to use the current class asthe listener How to use a named class as the listener How to use an anonymous class as the listener How to use an inner anonymous class asthe listener 198 ‘When to use each te How to handle high-level events... ow to handle events for check boxes and radio buttons 200 How to handle events for radio groups 202 How to handle events for spinners 204 How to handle events for seek bars 206 How to handle Key events How to handle Touch events The Tip Calculator app The user interfa ‘The Java code forthe activity How to work with themes and styles ‘An introduction to themes and styles... ‘Three themes. The theme framework that’s generated by Eelips. How to work with styles How to deine a style. How to apply a style How to erate a syle sheet How to work with themes. How to modify a theme How to modify the text appearance for a theme A summary of builtin themes How to apply themes How to work with colors. How to define colors How to apply colors How to work with menus and preferences How to work with menus. An introduetion to menus How to define a menu How to display an options men How to handle option menu events How to start anew activity How to work with preferences ‘An introduction to preferences How to define preferences How to display preferences in an activity 264 How to display preferences in a fragment 266Expanded contents Chapter 9 Chapter 10 How to get preferences. How to use preferences More skills for working with preference: How to group preferences: How to enable and disable preferences. How to use Java to work with preferences How to work with fragments An introduction to fragments Single-pane and multi-pane layouts, How to use support libraries, ‘The lifeeyele methods ofa fragment How to use single-pane layouts for small screens How to create the layout for a fragment How to create the class for a fragment How to display a fragment in an activity, How to create a preference fragment How to display a preference fragment in an activity How to use multi-pane layouts for large screens. How to add multiple fragments toa layout How to detect large screens How to detect sereen with How to contol the soft keyboard Other skills for working with fragments.. How to get a reference to a fragment How to replace one fragment with another The News Reader app How to work and intents An introduction to the News Reader app. The user interface ‘The XML for an RSS feed How to work with threads How threads work How to execute asynchronous tasks How to execute timed tasks How to update the UT thread How to work with files How to download a file from the Internet How to parse an XML file. ‘The RSSFeedHandler class ‘The RSSFeed class. ‘The RSSltem class How to work with adapters .. How to create the layout fora list view How to use an adapter to display data in alist view How to handle events for an adapter. h threads, files, adapters,Chapter 11 Chapter 12 Section 4 Chapter 13 Expanded contents How to work with intents, 348 How to pass data between activities 348 How to view a URL in a web browser 380 How to dial or calla phone numbes. 350 ‘The News Reader app 352 ‘The activity_items layout 352 ‘The ItemsActivity class. 354 The FilelO class 358, ‘The activity_item layout 358 ‘The lemAvtvity class 362 How to work with services and notifications How to work with the Application object, How to define the Application object How to register the Application abject. How to use the Application objec How to work with ser The lifecycle ofa service How to create a service How to register a service. How to start and stop a service How to use threads with services How to testa service How to view all services How to work with noti How notifications work How to create a pending intent How to create a notification How to work with system services.. How to display or remove a notification How to check if a network connection is available ‘The News Reader app ‘The NewsReaderService class ‘The ItemsActivity class. The FileIO class ations. How to work with broadcast receivers How to work with system broadcasts. ‘Asummary of the system broadcasts How to code a receiver for the boot completed broadcast. 414 How to code a seceiver for the connectivity changed broadcast 416 How to work with custom broadcasts .. How to create and send a custom broadcast How to code a receiver for a custom broadcast The Task List app How to work with SQLite databases An introduction to databases. The user interface for tae Task List app. 428 Aniitroduction to SQLite 430x Expanded contents Chapter 14 Chapter 15 An introduction to the Task List database: 432 ‘The business objects for the Task List app 434 How to create a database class. How to define the constants for a database. How to define the SQL statements that create a database. How to create or upgrade a database. How to open and close a database connection How to add public methods to a database class.. How to retrieve multiple rows from a table How to retrieve a single row from a table. How to get data from a cursor How to insert, update, and delete rows How to test the database class and cl How to test the database class How to clear test data from 8 device How to use the DDMS perspective to work with database files. How to use the SQLite Database Browser. s data, How to work with tabs and custom adapters How to use tabs . How to add the TabManager clase to your project 468 The layout for an activity that displays tabs 468 ‘The class for an activity that displays tabs 470 ‘The clas fora fragment that displays tab content 412 How to use a custom adapter ‘A layout fora list view item. ‘A class thal extends the layout fora ist view item, 416 ‘Acclass for a custom adapter 480 A class for a fragment that uses a custom adapter, 482 The Task List app. ‘The user interface ‘The activity_task_list menu. 485 ‘The TaskList Activity class 486 ‘The activity_add_edit and spinnes_list layout. 490 ‘The activity_add_edit men 490 ‘The AddBditActivity class 492 How to work with content providers An introduction to content providers URIs for content providers ‘MIME types for content providers ow to add supporting methods to the datanase class 502 How to create a content provider. How to start a content provider class. How to provide for querying. How to provide for inserting rows Tow to provide for updating rows How to provide for deleting rows. How to register a content provider. How to use a content provider. How to use a custom content provider How to use a builtin content providesSection 5 Chapter 17 Chapter 18 Expanded contents How to work with a dialog box. ow to import the dialog class and interface S18 How to build and show the dialog box 518 The Task History app. The user imerface ‘The XML for the layouts ‘The Java code forthe activity sa How to work with app widgets An introduction to app widgets. ‘A Home scrcen that has app widgets How to add app widgets to the Home screen 536 How to create app widgets .. How to create the layout How to modify the database class How to create the provider class How to configute an app widget How to register an app widget How to estan app widget Advanced Android skills How to deploy an app An introduction to distributi How distribution works How monetization works n and monetization. How to create a release build How to prepare an app for release How to create the signed APK file. How to distribute directly to the user How to distribute via a web site. How distribute via email How to publish on Google Play. How to set up a publisher account How to use the Developer Console to publish an app. How to view the listing for an app. How to work with locations and maps An introduction to locations and maps ‘The user interface forthe Run Tracker app. ‘An introduetion to determining location ‘An introduction to maps ‘An introduction to the Google Maps Android API How to configure the Google Maps Android API v2 How to add the Google Play services library toa project How to get the SHA-1 fingerprint. How to get a Maps API key How to register the Maps API key How to set permissions and featuresIntroduction How to work with locations.. How to connect to Google Play services How to get the current location, How to handle a failed connection How to get location updates. How to make sure GPS is enabled, How to work with Google Maps. How to add a map fragment to a layout How to display a map. How to zoom in on a location. How to add markers, How to add lines The Run Tracker app “The activty_run_map layout ‘The RunMapActivity class ‘The RunTrackerService classIntroduction Android is arguably the world’s most widely used operating system for mobile devices such as smartphones and tablets. As of May 2013, over 900 million Android devices had been activated and over 48 billion apps had been installed from the Google Play store. In the coming years, Android’s popularity is likely to continue for a couple reasons. First, Google releases Android under an open-source license that allows it to be modified and freely distributed by device manufacturers. Second, since Android is open-source with a large community of developers, it is able to evolve according to the needs of the developers who use it Who this book is for This book is for anyone who wants to learn professional skills for developing Android apps. The only prerequisite is a basic understanding of the Java programming language roughly equivalent to chapters | through 14 of our core Java book, Murach’s Java Programming. Once you have the necessary Java skills, this book should work for you even if you have absolutely no experience developing mobile apps. What version of Android this book supports The apps presented in this book have been designed to take advantage of the latest features of Android 4.2 and have been tested on this version of Android. However, most of these apps have also been designed to work with earlier versions of Android going back to version 2.2, and they have been tested on Android 2.2. Since Android is backwards-compatible, the apps presented in this book should continue to work for future versions of Android, though they might not take advantage of the latest features. For example, the apps in this book have been tested on Android 4.3, which was released just as this book went to press, and they work well with that version of Android.XIV Introduction What operating systems this book supports The software you need for developing Android apps is available for Windows, Mac OS X, and Linux. If you're using Windows, you can use Appendix A to download and install this software. If you're using Mac OS X, appendix B shows how to download and install this software. If you're using another platform such as Linux, you probably already know how to install this software! If not, you can use appendix B as a general guide and search the Internet for more information if you need it What IDE this book supports This book shows you how to use the Eclipse IDE (Integrated Development Environment) to code, test, and debug applications. Although there are other excellent IDEs for working with Android, I decided to present Eclipse because think it’s the most widely used IDE for Android development. In addition, it’s available for free, and it runs on all operating systems. Even if you want to use another IDE, I recommend that you use Eclipse to work with the applications presented in this book. Then, once you're done with this book, it should be easy for you to switch from Eclipse to another IDE, However, if you'd prefer to get started with another IDE right away, you can do that too, But first, you'll need to convert the Eclipse projects that are available from our web site so you can open them in your preferred IDE. Since the IntelliJ IDE has been gaining in popularity in recent years, appendix C shows how to install and configure IntelliJ to work with this book. In addition, it shows how to use IntelliJ to import the Eclipse projects for this, book. After that, you should be able to use this book with IntelliJ. If you hit any problems, you can search the Internet for solutions. In May of 2013, IntelliJ announced that itis collaborating with Google to create a new IDE called Android Studio. This IDE is based on the IntelliJ source code but streamlined for Android development. As this book goes to press, Android Studio is only available as an early access preview. However, since it's backed by Google and IntelliJ, it might become very popular after a production version is released, As a result, it's worth keeping an eye on this IDE for the next few years, How to get the software you need You can download all of the software that you need for this book for free from the Internet, This software includes the source code for this book, the Java SDK (Software Development Kit), and the ADT (Android Developer Tools) bundle, which includes the Android SDK, Eclipse, and the ADT plugin for Eclipse.Introduction XN What you'll learn in this book As I wrote this book, I did my best to focus on the practical features that you'll need for developing professional Android applications. Here's a quick tour: © Insection 1, you'll quickly master the basics of Android programming. In chapter 1, you'll learn some background terms and concepts. In chapter 2, you'll learn how to use Eclipse for Android development. In chapter 3, you'll learn how to develop your first Android app, a simple but complete Tip Calculator app. And in chapter 4, you'll learn how to use Belipse to thoroughly test and debug your apps ‘+ Insection 2, you'll learn some essential Android skills by enhancing the Tip Calculator app that you developed in chapter 3. To start, in chapter 5, you'll earn how to use different layouts and widgets to develop a sophisticated user interface. In chapter 6, you'll learn several techniques for handling high- and low-level events. In chapter 7, you'll learn how to use themes and styles to improve the appearance of your app. In chapter 8, you'll learn how to use menus and preferences. And in chapter 9, you'll learn how to use fragments to allow your app to take advantage of large screens that are available from some mobile devices such as tablets. ‘+ In section 3, you'll learn how to develop a News Reader app. Along the way, you'll learn more essential Android skills. In chapter 10, for example, you'll learn how to read an RSS feed from the Internet, save that data in a file, and display it on the user interface. In chapter 11, you'll learn how to use a service to download data for an app even when the app isn't running, and to notify a user when new data is available. And in chapter 12, you'll learn how to respond to actions that are broadcast by Android and its apps. © Insection 4, you'll learn how develop a Task List app that stores one or more to-do lists. In chapter 13, you'll learn how to create a database to store these lists. In chapter 14, you'll learn how to use tabs and a custom adapter to display these tasks on the user interface, In chapter 15, you'll learn how to use a content provider to allow other apps to work with the same data as this app. And in chapter 16, you'll learn how to create an app widget that can display some of this app’s data on a device's Home screen, ‘* In section 5, you'll learn how to deploy apps to the Google Play store. Then, you'll learn how to create a Run Tracker app that uses the Google Maps APLXvi Introduction Why you'll learn faster and better with this book Like all our books, this one has features to help you learn as quickly and ily as possible. Here are just three of those features. ‘To help you develop applications at a professional level, this book presents complete, non-trivial apps. For example, chapter 12 presents the final version of the News Reader app, chapter 16 presents the final Task List app, and chapter 18 presents a Run Tracker app. Studying these apps is a great way to master Android development. ‘* All of the information in this book is presented in our unique paired-pages format, with the essential syntax, guidelines, and examples on the right page and the perspective and extra explanation on the left page. This helps you Jearn more while reading less, and it helps you quickly find the information that you need when you use this book for reference. ‘+ The exercises at the end of each chapter give you a chance to try out what you've just learned and to gain valuable, hands-on experience with Android programming. They guide you through the development of some of the book’s apps, and they challenge you to apply what you've learned in new ways. And because most of these exercises start from code that you can download from our web site, you'll spend your time practicing new skills instead of doing busywork. How our downloadable files make learning easier To make learning easier, you can download the source code for all the apps presented in this book from our web site (www.murach.com). Then, you can view the complete code for these apps as you read each chapter, you can run these apps to see how they work, and you can copy portions of code for use in your own apps You can also download the starting points and solutions for the exercises in this book. That way, you don’t have to start every exercise from scratch. This takes the busywork out of doing these exercises. As a resull, you get more practice in less time. In addition, if you encounter a problem, you can easily check the solution. This helps you to keep moving forward with less chance that you'll get hung up on a minor issue. For more information about these downloads, please see appendix A (Windows) and appendix B (Mac).Introduction Support materials for trainers and instructors If you're a corporate trainer or a college instructor who would like to use this book for a course, we offer an Instructor's CD that includes: (1) a complete set of PowerPoint slides, (2) test banks, (3) additional chapter exercises that aren't in this book, (4) solutions to those exercises, (5) projects that the students start from scratch, and (6) solutions to those projects. To learn more about this Instructor's CD and to find out how to get it, please go to our web site at www.murach,com and click the Trainers link or the Instructors link. Or, if you prefer, you can call Kelly at 1-800-221-5528 or send an email to kelly@murach,com. A companion book ‘As you read this book, you may discover that your Java skills aren't as strong as they ought to be. In that case, I recommend that you get a copy of our core Jaya book (Murach’s Java Programming). This book will get you up to speed with Java and show you how to use all of the core skills you need for developing Android apps. In short, I think our Java book makes a great companion book for this Android book. Please let us know how this book works for you When I started writing this book, my goal was (1) to teach you Android programming as quickly and easily as possible and (2) to teach you the practical Android concepts and skills that you need for developing professional apps. Now, Thope Ihave succeeded, If you have any comments about this book, I would appreciate hearing from you at murachbooks@ murach.com. ‘Thanks for buying this book. I hope you enjoy reading it, and I wish you great success with your Android programming, Morne’. Jocl Murach, Author joe] @murach.com xviGet started fast with Android This section gets you started fast with Android programming. Chapter 1 introduces you to some important terms, concepts, and background information. Chapter 2 shows you how to use Eclipse to work with Android projects. Chapter 3 introduces you to the basic skills that you need for developing Android apps. And chapter 4 shows you how {o test and debug Android apps. To illustrate these skills, this section shows how to write, test, and debug a simple Tip Calculator app. This app calculates the tip you would give based on the amount of a bill. When you complete these chapters, you'll be able to write, test, and debug simple applications of your own,An introduction to Android This chapter introduces you to the concepts and terms that you need for developing Android apps. To give you a clear idea of how the code for an Android app works, this chapter presents some of the code for a simple app that calculates tips. When you finish this chapter, you'll be ready to get started with Android development. Android overview... “Types of devices. ‘Types of apps brief history Versions System architecture How apps are compiled and run 4 A simple Android app .. The user imerface ‘The XML for the user imerface, 18 ‘The XML for the display text 22 ‘The Java source code 24 ‘The Android manifest. 28 PerspectiveSection | Get started fast with Android Android overview Android is a Linux-based operating system designed primarily for touch- sereen mobile devices such as smartphones and tablet computers. Before you begin developing apps that run on Android, it’s helpful to take a moment to consider the types of Android devices and apps that are available today. In addi- (ion, it’s helpful to understand the history, versions, and architecture of Android, Types of devices Figure 1-1 starts by showing two of the most popular Android devices, a smartphone and a tablet. However, the code for Android is open-source. Asa result, it can be customized to work with other types of electronic devices such as eBook readers, cameras, home automation systems, home appliances, vehicle systems, game consoles, and so on.Chapter 1 An introduction 10 Android An Android phone and tablet Other types of Android devices + Readers + Cameras + Home automation systems © Home appliances * Vehicle systems © Game consoles Description © Android is a Linux-based operating system designed primarily for touchscreen mobile devices such as smartphones and tablet computers. * Since the code for Android is open-source, it can be customized to work with other types of electronic devices. Figure 1-1. Types of Android devicesSection | Get started fast with Android Types of apps Android has a large community of developers writing applications, more commonly referred to as apps, that extend the functionality of Android devices. Figure 1-2 lists some categories of different types of apps and describes some of the functionality available from each category. As you review this list, keep in mind that these categories are only intended to give you a general idea of the various types of Android apps. More categories exist, and the functionality that’s available from Android apps is constantly expanding If you have used a smartphone or tablet, you should be familiar with some of the apps listed in this figure. For example, you probably use apps to send and receive text messages and email. You probably use apps to take pictures, listen to music, and watch video. You probably use apps to get directions and navigate to a location. You probably use apps to check the weather, read news, and browse the web, In addition, you may use apps from social media companies like Facebook and Twitter to work with social media. You may use apps to play games like Angry Birds. The main point here is that there are many different types of apps and that application developers are constantly creating new apps that use the capabilities of Android phones in new ways ‘Some apps come preinstalled on the device. For example, most phones include apps for managing contacts, using the phone, sending and receiving text messages and email, working with photos and video, and web browsing. Other apps are available for download through Google Play or third-party sites. Some apps are free. Other apps are expensive. All apps were cteated by somebody like you who learned how to develop Android apps.Chapter 1 An introduction 10 Android Types of Android apps een Communications Send and receive tent messages, send and receive email, make and receive phone cals, manage contacts, browse the web Photography Take photos, edit photos, manage photos. Audio Play audio, record audio, edit audio Video Play video, recond video, eit video Weather View weather reports News Read news and blogs. Personalization Organize home screen, customize ringtones, ustomize wallpaper, Productivity ‘Manage calendar, manage task list, take notes, make calculations. Finance ‘Manage bank accounts, make payments, manage insurance poli- cies, manage taxes, manage investment portfolio. Business Read documents, edit documents, track packages. Books Read and search eBooks. Reference Get info from a dictionary, thesaurus, or wiki, Education Prepare for exams, learn foreign languages, improve vocabulary. Shopping Buy items online, use electronic coupons, compare prices, keep grocery lists, read product reviews. Social ‘Use social networking apps such as Facebook and Twitter. Fitness ‘Monitor and document workouts. Sports ‘Track sport scores, manage fantasy teams. Travel Get directions, use GPS to navigate toa location, get information about nearby places to visit Games Play games such as arcade games, action games, puzzles, card ‘games, casino games, sports games. Description * Android has a large community of developers writing applications, more commonly referred to as apps, that extend the functionality of Android devices. Android apps are available for download through Google Play or third-party sites. Figure 1-2 Types of Android appsSection | Get started fast with Android A brief history Figure 1-3 summarizes the history of Android. In 2003, a handful of entre- preneurs in Palo Alto, California, founded Android, Inc. In 2005, Google bought Android, Inc, Then, in 2007, the Open Handset Alliance was announced. This alliance consists of a consortium of hardware, software, and telecommunication companies devoted to advancing open standards for mobile devices. That same year, Google released Android code as open source under the Apache License. In addition, Google helped to create the Android Open Source Project (AOSP) and put it in charge of the maintenance and further development of Android. In 2008, the first version of the Android Sofiware Development Kit (SDK) was released. This SDK contains all of the tools that Android developers need to develop apps. Later in 2008, the first Android phones became available. Since 2008, new versions of the Android SDK have continued to be released, and Android devices have continued to proliferate. During that time, hundreds of thousands of apps have been developed, and billions of apps have been downloaded.Chapter 1 An introduction 10 Android A brief history of Android ‘Android, Inc. is founded in Palo Alto, California Google buys Android, Inc ‘The Open Handset Alliance is announced. This alliance consists of a consortium of hardware, software, and telecommunication companies devoted to advancing open standards for mobile devices. Google releases Android code as open source under the Apache License, ‘The Android Open Source Project (AOSP), led by Google, is tasked ‘with the maintenance and further development of Android. Android Software Development Kit (SDK) 1.0 is released. This kit ‘contains all of the tools needed to develop Android apps. ‘The first Android phones become available. 2009-present New versions of the Android SDK continue to be released. Android devices continue to prolifecate. Hundreds of thousands of apps are developed. Billions of apps are downloaded. Description » Android has grown steadily since its release in 2008 until the present. Figure 1-3 Abtief history of Android10 Section | Get started fast with Android Versions Figure 1-4 describes all major releases of Android starting with version 1.6 and ending with version 4.3. Here, each version of Android corresponds with an API (Application Programming Interface) number. For example, version 4.2 corresponds with API 17, and version 2.2 corresponds with API 8. In addition, each version has a code name that’s based on something sweet. For example, version 2.2 carries the code name Froyo, while version 4.1 is known as Jelly Bean. ‘As you develop an Android app, you must decide the minimum API level that your app supports, As of April 2013, many developers choose 7 or 8 as the minimum API level to support since that covers a high percentage of all Android devices. ‘The distribution percentages shown here are from April 2013. As time progresses, more users will upgrade from older devices to newer ones. As a result, you should check the URL shown in this figure to get current percentages before you decide the minimum API level for your app. ‘As you review this figure, you may notice that it doesn’t include some versions of Android such as 1.0 and 1.1. That's because there are virtually no devices left that run on these versions of Android. As time marches on, it’s inevitable that the same fate will befall other older versions of Android too.Chapter 1 An introduction to Android 1 Android versions onion 16 21 22 23-232. 233-237 32 403-404 4a 42 43 Crone Sd Donut Belair Froyo Gingerbread Honeycomb Tee Cream Sandwich Jelly Bean A URL for current distribution percentages ttp://developer.android.con/about dashboards Description ‘+ Many new versions of Android were released from 2009 to 2012. + The distribution percentages in this figure are from April 2013. To get current percentages, please visit the URL shown above. * As you develop an Android app, you must decide the minimum API level that your app supports. As of April 2013, many developers choose Android 2.2 as the minimum API level to support since that covers a high percentage of all Android devices. Figure 1-4 Android versions12 Section | Get started fast with Android System architecture Figure 1-5 shows the Android system architecture, which is also known as the Android stack. This stack has four layers. The bottom layer of the stack is Linux, an open-source operating system that's portable and secure. This operating system provides low-level drivers for hardware, networking, file system access, and inter-process communication are). The second layer up in the stack contains the native libraries. These libraries are written in C or C++. They include the Dalvik virtual machine (VM), which works similarly to the Java virtual machine (JVM). However, the Dalvik VM was designed specifically for mobile devices and their inherent limitations, such as battery life and processing power. The third layer up in the stack contains the application framework. This layer is written mostly in Java, and it provides libraries that can be used by the (op layer of the stack. In this book, you'll learn how to use some of these librar- ies, such as the libraries for the notification manager, content providers, and the location manager. The top layer of the stack contains Android apps. These apps include pre-installed apps such as the apps that you can use to manage the home screen, manage your contacts, make and receive calls, browse the web, and so on. In addition, these apps include other apps that you can download and install. These types of apps are written in Java, and they are the type of apps that you'll learn {o develop in this book.Chapter 1 An introduction to Android 13 Android stack == =a —— aa =a = Cor i Linux Kernel Fi ‘Audio Pos pag Card Coa Description ‘© Linux is an open-source operating system that’s portable and secure. © The native libraries are written in C or C++. These libraries provide services to the Android application layer. * The Dalvik virtual machine (VM) works similarly to the Java virtual machine (JVM). However, the Dalvik VM was designed specifically for mobile devices and their inherent limitations such as battery life and processing power. © The application framework provides libraries written in Java that programmers can use to develop Android apps. Figure 1-5 The Android system architecture14 Section | Get started fast with Android How apps are compiled and run When you develop an Android app, you typically use an IDE (Integrated Development Environment) such as Eclipse to cteate a project. A project contains all of the files for the app including the files for the Java source code. In the next chapter, you'll leam how to use Eclipse to work with Android projects. When you're ready to test a project, you can run it, Figure 1-6 shows how this works, When you run a project, the IDE typically compiles and packages the project automatically before running it. This is known as building the project. When the IDE builds a project, it compiles the Java source code (java files) into Java bytecodes (.class files), Then, it compiles the Java bytecodes into Dalvik executable files (.dex files) that can be run by the Dalvik virtual machine that’s available from all Android devices. When the IDE builds a project, it puts the .dex files and the rest of the files for the project into an Android package (.apk file). This file contains all of the files necessary to run your app including the .dex files and other compiled resources, uncompiled resources, and a binary version of the Android manifest. The Android manifest is a file that specifies some essential information about an app that the Android system must have before it can run the app. In its non-binary version, the Android manifest is stored in a file named AndroidManifest.xml, For security reasons, all Android apps must be digitally signed with a certifi- cate. During development, the IDE typically signs the app for you automatically using a special debug key. Then, it runs the app on the specified physical device such as a smartphone or tablet. Or, it runs the app on the specified emulator, which is a piece of software that runs on your computer and mimics an Android device. An Android emulator can also be called an Android Virtual Device (AVD). The Android debug bridge (ADB) lets your IDE communicate with an emulator or a physical Android device. This is necessary to provide the debug- ging capabilities described in chapter 4 When you are ready to release the app, you must sign the app in release mode, using your own private key. For more information about this, please see chapter 17,Chapter 1 An introduction to Android 15 Android system architecture Perr (pk) | citer | ADB. ey erate] rr) ots Paretg Camas Description © When you develop an Android app, you typically use an IDE (Integrated Development Environment) such as Eclipse to create a project, and you typically use Java as the programming language. © When you develop an Android app, you can run it on a physical Android device, such as a smartphone or tablet. Or, you can run it on an emulator, which is a piece of software that runs on your computer and acts like an Android device. An Android emulator can also be called an Android Virtual Device (AVD). * Before you can run a project, you must build the project. Typically, the IDE auto- matically builds a project before running it. ‘© When the IDE builds a project, it compiles the Java source code (java files) into Java bytecodes (.class files) and then into Dalvik executable files (dex files). Dalvik executable files can be run by the Dalvik virtual machine that’s available from all Android devices. + When the IDE builds a project, it puts the files for the project into an Android package (apk file). This file contains all of the files necessary to run your app on a device or emulator including the .dex files, compiled resources (the resources.arse file), uncompiled resources, and a binary version of the AndroidManifest xm file © Torun an app on an emulator or device, the app must be signed with a digital certificate that has a private key. During development, the IDE automatically signs the app for you in debug mode using a special debug key. Before you release an app, you must sign the app in release mode, using your own private key. For more information about this, please see chapter 17 * The Android debug bridge (ADB) lets your IDE communicate with an emulator or a physical Android device. Figure 1-6 How an Android app is compiled and run16 Section | Get started fast with Android A simple Android app To give you a better idea of how an Android app works, this topic presents a basic Tip Calculator app. For a simple app like this one, the programmer only needs to modify three files: the XML file for the user interface, the XML file for the display text, and the Java source code for the activity. In addition, the programmer may sometimes need to view or modify the Android manifest file for the app. The user interface Figure 1-7 shows the user interface for the Tip Calculator app after it has been displayed in an emulator for Android 4.2 (API 17). Of course, this app can also be run on emulators for other Android platforms. Similarly, this app can also be run on a physical device that’s configured for debugging, The emulator shown in the figure includes a message that indicates that the hardware keyboard is not enabled in AVD and that you should use the on-screen keyboard, As a result, you can use the on-screen keyboard, known as a sof keyboard, to enter text as shown in this figure, To do that, you click on the Bill Amount text box. When you do, the emulator should display a soft keyboard that’s optimized for entering a number with a decimal point. When you're done using that keyboard to enter an amount for the bill, you can click the Done key. When you do, the app calculates the tip and total for the bill If the Hardware Keyboard option is enabled for an emulator, the emula- tor should display a message that indicates that you can use your computer's keyboard to enter text. In that case, the emulator won't display a soft keyboard when you click on the Bill Amount text box. Instead, you use your computer's keyboard to enter text. Although this provides an easier way to enter text, it doesn’t accurately emulate touchscreen devices, By default, this Tip Calculator app uses a tip percent of 15%, However, if you want to increase or decrease the tip amount, you can click the Increase (4) or Decrease (-) buttons. When you do, the app recaleulates the tip and total amounts for the bill.Chapter 1 An introduction to Android 17 The Tip Calculator app with the soft keyboard displayed @ Tip calculator Bill Amount 34.60, Percent 15% Tip $5.19 $39.79 Description © The Tip Calculator app shown in this figure is displayed in an emulator for Android 4.2 (API level 17). * Ifthe Hardware Keyboard option is not enabled for an emulator, you can use the on-screen keyboard, known as a soft keyboard, to enter text as shown in this figure. + Ifthe Hardware Keyboard option is enabled for an emulator, you can use your computer's keyboard to enter text To calculate a tip, click the Bill Amount text box and enter the bill amount, When you're done, press the Done key. © To increase or decrease the tip amount, click the Increase (+) or Decrease (-) buttons. The app automatically recalculates the tip and (otal amounts whenever the user changes the bill amount or tip percent. Figure 1-7 The user interface for the Tip Calculator app.18 Section | Get started fast with Android The XML for the user interface Figure 1-8 shows the XML for the user interface. This code defines an activ- ity, which is a screen that users can interact with, and it’s stored in a file named activity_tip_calculator.xml, If you have experience with XML or HTML, you may be able to understand much of this code already. If not, don’t worry! You'll learn the details about how this code works in chapter 3, For now, here's a brief explanation. ‘An XML file consists of one or more elements. These elements can be nested within cach other. In this file, the RelativeLayout element is the parent element, and it has ten child elements: seven TextView elements, one EditText clement, and two Button elements Hach of these elements has multiple attributes. For example, the RelativeLayout element has a padding attribute that determines how much space there is on the screen between the RelativeLayout element and its child elements. Many of these attributes are set automatically for you when you use a graphical tool like Eclipse to create the layout. As a result, you often don’t need to set these attributes, However, you sometimes need to modify them. The RelativeLayout element defines a layout, which is a container that determines where its child elements are displayed on the screen. In Android, there are several types of layouts that use different techniques to control where the child elements are displayed. The relative layout organizes its child elements in relation to one another. The RelativeLayout element has several attributes that determine how it works. Here, the first two attributes are set automatically, and you can usually ignore them. Thea, the layout_width and layout_height attributes determine that the layout should use the whole sereen. Finally, the padding altribute determines that there should be some padding, or space, between the edge of the layout and its child elements. To specify the amount of space, the padding attribute specifies a measure- ment of “10dp”. Here, dp stands for density-independent pixel. In general, it’s considered a best practice to use density-independent pixels for padding and margins whenever possible as it allows your app to scale properly on various devices. The child clements define the controls for the bill amount. In Android, controls are typically referred to as widgets. The first TextView element displays “Bill Amount” on the user interface. In Android terms, this element is often referred to as a text view. Since this widget displays text that labels another widget, it can also be referred to as a label. The first atribute of this widget defines an ID for the widget. Here, the value for the id attribute begins with “@+id/”. This indicates that the following text is, the ID for the widget. In this case, the widget has an ID of billAmountLabel. The next three attributes for this widget set its height, width, and padding,Chapter 1 An introduction 10 Android The activity_tip_calculator.xml Page 1 ‘nt tp: //schenas-android.con/apk/res/androia” watch_parent™ ayout_height="match parent" android:padding="10ap" >
The tip percent
Figure 1-8 The XML for the user interface (part 1 of 3)20 Section | Get started fast with Android The fifth attribute sets the text that's displayed on the widget to the value that's stored in the bill_amount_label string of the strings.xml file, which you'll Jearn about in a moment. To get a string from the strings.xml file, the value for this attribute begins with “@string/”. This indicates that the following text is the name of the string element that contains the text. To specify the size of the text, the textSize attribute specifies a measurement of *20sp”. Here, sp stands for scale-independent pixel. In general, it’s considered a best practice to use scale-independent pixels for text sizes whenever possible as it allows your text sizes to scale properly. Finally, the textStyle attribute sets the style of this text to bold. The EditText clement that follows displays the widget that allows the user to enter a bill amount. The Android documentation refers to this type of widget as an editable text view, but you can also refer to it as a text box. Most of the attributes of this EditText element work similarly to those of the previ- ous TextView element. However, there are some differences. For example, the alignment attributes align the text box relative to its label. Then, the ems attribute specifies that the text box width should be 8 ems (8 of the letter m). Next, the inputType element specifies that the soft keyboard should only allow the user to enter decimal numbers. To make it easy to test this app, the text attribute for the EditText element specifies a default value of “34.60”. During development, you can leave this altribute set to a default value like this one. However, once the application is working, you can set this attribute to an empty string. The next two TextView elements define the widgets that display the tip percent, By now, you should have a general idea of what most of the attributes do. The main point to notice is that the layout attributes align these controls rela tive to one another. For example, the label for the tip percent is aligned with the left side of the label for the bill amount, Similarly, the percent label is displayed below the bill amount label, The Button elements define the buttons that allow the user to increase or decrease the tip percent. These widgets are 45dp wide and high and they're aligned to the right of the TextView widgets for the tip percent. The last four Text View elements define the widgets that display the tip and total amounts. These elements work like the previous TextView elements shown in this figureChapter 1 An introduction to Android 24 The activity_tip_calculator.xml file Page 2 andzoid:id="9+id/percentDowaButton" android android:layout_height="45ap" android: layout _alignBaseline="@sid/percentTextView" sndroid:layout_narginiett=r2sdp- android :layout_tonightof="@+id/percentTextView* android: text-"@string/decrease android:textsize="20ap" />
Figure 1-8 The XML for the user interface (part 2 of 3)22 Section | Get started fast with Android The XML for the display text Part 3 of figure 1-8 also shows the XML for the display text. This XML is stored in a file named strings.xml, and it defines the names and values for the display text. For example, the string element with a name of app_name has a value of “Tip Calculator”. The string element with a name of bill_amount_label has a value of “Bill Amount”. The string element with a name of bill_amount has a value of 34.60", And so on. To differentiate between the widgets that display labels and the widgets that display results, have appended “label” to the names of the labels. At this point, you may be wondering why Android provides a mechanism for separating the display text from the user interface. The reason is because Android apps are likely to run on devices used around the world. As a result, Android attempts to make it easy to develop apps that are appropriate for differ- ent locales. This is known as localization. For example, you can provide one strings.xml file for English and another for French. Then, if Android determines that the locale for the device is French, it will use the strings.xml file that contains the French text. You’ll learn more about how that works in chapter 3Chapter 1 An introduction 10 Android The activity_tip_calculator.xml file Page 3
The strings.xml file
Tip Calculator
Tip Calculator
Bill Amount
«string ‘pill amount ">34.60
Percent
+
~
Tip
$0.00
Total
$0.000 Description * In Android development, an activity is a screen that users can interact with. ‘The activity_tip_calculator.xml file contains the XML that defines the user interface, ‘The strings.xml file contains the XML for the text strings that are displayed in the user interface. Figure 1-8 The XML for the user interface (part 3 of 3) 2324 Section | Get started fast with Android The Java source code Figure 1-9 shows the Java source code that handles events that occur on the user interface, gets input from the user interface, performs calculations, and updates the user interface, This source code is stored in a file named TipCalculatorActivity.java. If you have experience with Java, you may be able to understand much of this code already. If not, don’t worry! You'll Iearn the details about how this code works in chapter 3. For now, here’s a brief explanation. This source code declares a class named TipCalculatorActivity. To start, the package statement stores this class in the com.murach.tipcalculator package. Then, it imports all the Java and Android classes and interfaces that are needed for this class. As you can see, most of these classes and interfaces are stored in the android. view or android widget packages. The TipCalculatorActivity class inherits the Activity class that’s provided by Android. This class defines the methods that are called during the lifecycle of an activity. This allows the TipCalculatorActivity class to overtide these lifecycle methods to perform tasks at different points in the activity’s life. Of these methods, the most important one is the onCreate method, which is called when Android creates an activity. This method is the only lifecycle method that's used by the activity shown in this chapter. However, in chapter 3, you'll learn how to use two other activity lifecycle methods to save and restore data if the activity is interrupted by another activity such as a phone call. The TipCalculatorActivity class also implements (wo interfaces, These interfaces allow this class to handle the events that occur on the user interface. First, the OnEditorActionListener interface makes the class a listener for the EditorAction event. As a result, this class must implement the onEditorAction method. Then, the OnClickListener interface makes the class a listener for the Click event. As a result, this class must implement the onClick method, Within the class, the first six statements define the instance variables for the widgets that the class needs to work with. Then, the seventh statement defines an instance variable for the tip percent and sets its default value to .15. Since this, statement uses the float type, this code appends an fto the number to indicate that the literal is of the float type, not the double type. The onCreate method begins by passing its Bundle parameter to the super~ class (the Activity class). Then, it uses the setContentView method that's avail- able from the Activity superclass to display the user interface that's defined in the activity_tip_calculator.xml file, To do that, this method uses the R class to access the compiled resources that are available to the Android app. This class is created and compiled automatically when you build a project. In other words, Android converts the XML in the activity_tip_calculator.xml file into Java code, compiles it, and makes it available through the R class.Chapter 1 An introduction 10 Android The TipCalculatorActivity,java file Page 1 package com.murach.tipcalculator; import java.text NumberFormat; import android.os.Bundli import android view.KeyEvent; import android -view.view: import android view.view.onClickListene) import android widget.Button; import android widget .RaitText; import android widget Textvier import android widget TextVi import android app.Activity; public class TipcalculatorActivity extends Activity implements OnEditoractionListener, OnClickListener ( // aefine instance variables for the widgets private EditText billAncuntEditrext; private TextView percentTextView; private Button percentUpButton; private Button percentDownButton; private TextView tipTextView, private TextView totalvextviews // fine an instance variable for tip percent private float tipPercent = .15f; Goverriae public void oncreate(Bundle savedinstancestate) ( super.onCreate(savedinstancestate); setContentView(R.layout activity tip_calculator); 1] get references to the widgets billanountEaitText = (EditText) fndViewByrd(R.id.billamountEaitrext); percentTextView = (TextView) findViewById(R.id-percentTextView); PercentUpButton = (Button) findViewByrd(R.id.percentUpButton); percentDownButton = (Button) findViewsyid(R-id.percentDownButton); tiprextView = (TextView) findViewByrd(R.id.tipTextView); totaltextview = (TextView) findViewsyrd(R.id.totalTextView); 1] get the listeners billAnountEaitText setonEditerActionListener (this); percentUpButton.setOnClickListener(thia); percentDownButton.setOnClickListener (this); // calculate the tip and display the results ealculateandDisplay(); Figure 1-9 The Java source code (part 1 of 2) 2526 Section | Get started fast with Android After displaying the user interface, the onCreate method gets references to the six widgets that it declared earlier. To do that, it calls the findViewById method for each widget and uses the R class to pass the ID of the widget to that method. Then, it casts the widget abject that’s returned to the appropriate type. These types correspond with the names of the elements in the XML file for the user interface After getting references to the widgets, this code sets the listeners. First, it sels the current class (TipCalculatorActivity) as the listener for the EditorAction event on the bill amount text box. As a result, the onEditorAction method in this class is executed when the user uses the bill amount text box to enter an amount for the bill. Then, this code sets the current class as the listener for the Click event on both of the buttons. As a result, the onClick method is executed when the user clicks on either button. ‘After setting the listeners, this code calls the calculateAndDisplay method This method calculates the tip and total amounts and displays all current data on the user interface. To start, it gets the string that was entered into the bill amount text box. Then, it checks whether the string is empty. If so, it sets the bill amount to zero. Otherwise, it converts the string to a float value. Next, it calculates the tip and total amounts. Finally, it formats and displays the results of the calculations. To do that, it uses the NumberFormat class to convert the float values into string values that have currency and percent formatting The onEditorAction method is executed whenever the user presses an action key on a soft keyboard such as the Done key. This method calls the calculateAndDisplay method to calculate the new tip amount and total and display it on the user interface. The onClick method is executed whenever the user clicks on either of the buttons. This method begins by using a switch statement to check which button is clicked. Then, if the Decrease (-) button is clicked, this code decreases the tip percent by 1 percent and calls the calculateAndDisplay method to refresh the data that’s on the user interface. Conversely, if the Increase (+) button is clicked, this code increases the tip percent by 1 percent and calls the calculateAndDisplay method to refresh the data.Chapter 1 An introduction to Android 27 The TipCalculatorActivity,java file Page 2 public void calculateandDisplay() ( 7 get the bill amount String billAmountstring = billamounteditText float billamount; if (billaAmountstring.equals("™)) ( billamount = 0; eText () testring(); « billAmount = Float.parseFloat (billAmountstring); > 1] calculate tip and total float tipAmount = billAmount * tipPercent; float totalAmount = billAmount + tipAmount; // display the results with formatting NumberFormat currency = NumberFormat.getCurrencyInstance(); tiprextView.setText (currency.format (tipAmount)}; totalTextView.setText (currency. format (totalAmount)); NumbexFormat percent = NumberFormat.getPercentInstance( percentTextView.setText (percent format (tipPercent)); > override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) ( calculateAndDisplay(); return false; > soverride public void onclick(view v) ¢ switch (vgetra()) ¢ case R.id.percentDownButton: tipPercent = tipPercent - .01f; calculateandDisplay(); case R.id.percentupButton: tiprercent = tippercent + .01f; calculateandDisplay(); break; Figure 1-9 The Java source code (part 2 of 2)28 Section | Get started fast with Android The Android manifest Figure 1-10 shows the AndroidManifest.xml file, which is known as the Android manifest. This file specifies some essential information about an app that the Android system must have before it can run the app. Within the manifest, there is always one application element. Within the application element, there may be one or more activity elements. However, for this app, there is only a single activity. This activity is identified as the main activity, and it is launched when the app starts. Like the XML file for the user interface, the manifest file can access strings in the strings.xml file. For example, the label attribute of the application element specifies the app_name string in the strings.xml file, Similarly, the label attribute of the activity element specifies the title_activity_tip_calculator string in the strings.xml file. This manifest file sets the screenOrientation attribute of the activity to “portrait”, As a result, this application can only be displayed in portrait orienta- tion, not landscape orientation. That's important because this activity doesn’t include the code that’s necessary to gracefully handle the switch between the portrait and landscape orientations. In chapter 3, you'll leam how to handle changes in orientation.Chapter 1 An introduction 10 Android 29 The AndroidManifest.xml file «manifest xnIns:android="http://achemas package="com.murach.tipcalculator™ ndroid.com/apk/zes/androia” cactivity android:nane=".TipCalculatorActivity" android:label="@string/titie activity tip_calculator" android:acreenorientation="portrait">
vandroid.intent .category.LAUNCHER* />
Description * The Android manifest (the AndroidManifest xml file) specifies some essential information about an app that the Android system must have before it can run the app, including the first activity to launch when the app is started. Figure 1-10 The Android manifest file30 Section | Get started fast with Android Perspective The goal of this chapter has been to introduce you to some concepts and terms that you should understand before getting started with Android program- ming, However, this chapter is just an overview of Android programming. In the next few chapters, you'll learn the hands-on skills you need to develop a simple Android app like one shown in this chapter. Terms Android Android Virtual Device (AVD) application Android debug bridge (ADB) app soft keyboard Open Handset Alliance activity Android Open Source Project (AOSP) element. Software Development Kit (SDK) parent clement Android stack child element Dalvik virtual machine (VM) attribute Java virtual machine (JVM) layout Integrated Development Environment relative layout (DE) padding project density-independent pixel (dp) building control Java source code widget Java bytecodes text view Dalvik executable files label Android package scale-independent pixel (sp) Android manifest editable text view signed app text box emulator localizationChapter 1 An introduction 10 Android 31 Summary © Android is a Linux-based operating system designed primarily for touch- screen mobile devices such as smartphones and tablet computers. It was first released in 2008, Android code is open-source Android developers write applications, ot apps. ‘+ Android system architecture, known as the Android stack, consists of four layers: Linux, native libraries, the application framework, and Android apps, * An Android app is typically developed using an IDE (Integrated Development Environment) like Eclipse, using Java as the programming, language. ‘+ Android apps can be run on a physical Android device or on an emulator, also called an Android Virtual Device (AVD). * An Android project must be built before it is run, compiling the Java source code (java files) into Java bytecodes (.class files) and then into Dalvik executable files (.dex files). + Allof the files for an Android project are put into an Android package (apk file), which includes a binary version of the AndroidManifest xml file, © Torun an app on an emulator or device, it must be digitally signed with a certificate. © The Android debug bridge (ADB) lets your IDE communicate with an emulator or a physical Android deviceHow to use Eclipse for Android development Eclipse is an Integrated Development Environment (IDE) that you can use to develop Android apps. Eclipse is open-source, available for free, and runs on all modern operating systems. Although it's possible to use other IDEs, Eclipse has support from most of the Android development community, including many of the developers at Google who helped develop Android. As result, most Android developers use Eclipse. How to work with existing projects . ‘An introduction to Eclipse projects How to set the workspace How to importa project into the workspace How to remove a project from the workspace. How to work with the user interface How to work with other XML resources. How to work with the Java code. How to set the run configuration How to run an app on a physical device. How to runan app on an emulator How to work with a new project. How to create a new project How to work with the starting code How to use the cade completion feature How to detect and correct errors and warnings 6 The Tester app ‘The user imerface ‘The XML for the use interface 66 ‘The Java source code: 66 Perspective34 Section | Get started fast with Android How to work with existing projects If you read chapter 1, you're ready to start working with existing Eclipse projects. In particular, you're ready to learn how to open and run any of the applications for this book. You can download these applications from our web site as described in the appendix. troduction to Ec! se projects When you first start Belipse as described in the appendix, you may notice that it displays a splash screen that says, “Android Developer Tools”. In addi- tion, the title bar for the application uses a green icon instead of the traditional blue Fclipse icon and says ADT instead of Eclipse, That's because the appendix shows how to install a version of Eclipse that has been customized to include the Android Developer Tools (ADT). Figure 2-1 shows the Belipse workbench, which is where you work in Eclipse. The different parts of the workbench are known as views. In this figure, for example, the workbench shows the Package Explorer view, the Outline view, and the Console view. In this figure, the Package Explorer only contains one project, which is a directory that contains all the files for an app. This lone project is for the Tip Calculator app. However, it’s common to import several projects into the work- bench. Then, you can use the Package Explorer to view all of the projects that you have imported. Within a project, the src directory contains the Java source code. Within the sre directory, the java files can be organized into packages. In this figure, the project has a single package named com.murach.tipcalculator. Within this pack- age, the project has a single .java file named TipCalculatorActivity java. In this, figure, this file is open in the Java code editor. You'll learn more about working with this code editor later in this chapter. Within a project, the res/layout directory contains the XML file or files that define the layout of the user interface. In this figure, the project has a single XML layout file named activity_tip_calculatorxml. You'll lean more about working with this XML file later in this chapter. Within a project, the res/values directory contains the XML file that defines the display text for the user interface, These strings are stored in a file named strings.xml. Again, you’ll learn more about working with this XML file later in this chapter.Chapter 2 How to use Eclipse for Android development 35 eee saaam [Tecan ner ocerictiealeleers Talents nahoactionvtny nessa sia orete nnn settee) ( Description * When you first start Eclipse, it may display a Welcome page. If so, you can click the Workbench icon to go to the workbench, which is where you develop apps. The workbench contains multiple views such as the Package Explorer, Outline, and Console views * The workbench provides code editors for working with Java and XML files. * An Eclipse project consists of a top-level directory that contains the subdirectories and files for an application. The sre (source) directory contains the Java packages that store the source code ava files) for the project. Within the sre directory, the java files can be organized into one or more packages, where each package corresponds with a subdirectory. * The res (resources) directory contains other resources for the project, including the XML files that define the user interface. * The directories, files, and libraries that make up a project are listed in the Package Explorer. If this view isn’t visible, you can display it by selecting the Window Show View>Package Explorer item. * You can expand and collapse the nodes of the Package Explorer by clicking on the triangles to the left of each node. Figure 2-1 An introduction to Eclipse36 Section | Get started fast with Android How to set the workspace Figure 2-2 shows how to set the workspace for an Eclipse session. The workspace is the directory that’s used by Eclipse to store the subdirectories and files it needs to work. If you download and install the source code for this book as described in the appendixes, the workspace for this source code is available here: \murach\android\workspace Asa result, the easiest way to get started with the source code that’s available for this book is to use the Workspace Launcher dialog box to specify this workspace. Then, you can use this workspace when working on projects from this book, and you can use another workspace when working on other projects.Chapter 2 How to-use Eclipse for Android development. 37 The Workspace Launcher dialog box Select a workpsce 201 tre you pots ina folie ced wotpace Chests wrap Tole tetris een Voice SET Copy Sets @ How to switch the Eclipse workspace 1. Start Relipse. 2. Select the File->Switch Workspace Other item from the menu bar. This should display the Workspace Launcher dialog box. 3. Click the Browse button and use the resulting dialog box to select the workspace directory. When you do, Eclipse will restart and load the new workspace. Description + In Felipse, a workspace is a directory that stores information about how to configure the workbench and which projects to display. In addition, the workspace typically contains the directories and files for the projects, though it’s possible to store a project outside of the workspace. Once you have set a workspace, it will appear in the Switch Workspace menu, and you can select it to switch to it. As a result, it’s easy to switch between existing workspaces, Figure 2-2 How to set the workspace38 Section | Get started fast with Android How to import a project into the workspace Figure 2-3 shows how to import an existing project into a workspace. To do that, select the Import item from the File menu. In the first dialog box, expand the node for the General category and select the Existing Projects into Workspace option. In the second dialog box, click the Browse button and select, the directory that contains the project or projects that you want to import. When you do, all of the possible projects will be displayed in the Projects list box 50 you can select the ones you want to import. In this figure, for example, the project for the Tip Calculator app presented in chapter 3 is selected. As a result, clicking the Finish button imports this project into the current workspace. Often, when you import an existing project, the directory that you specify in the Import dialog box is in a subdirectory of the current workspace. In that case, you don’t need to use the “Copy projects into workspace” check box since the project is already in the workspace. However, if you specify a directory other than the directory for the current workspace, you may want to select the “Copy projects into workspace” check box. That way, the directories and files for the projects that you select will be copied into the current workspace, and the changes you make to these projects won't change the directories and files in the original location. On the other hand, if you want your changes to these projects to affect the directories and files in the original location, don’t select the “Copy projects into workspace” check box.Chapter 2 How to use Eclipse for Android development The dialog box for importing an existing project npn Proce 2 Conde esemh ig epi to, @ seetnt eee CmantiunidnersctboompA (Bae) Set ct ie = Pree [a8 recor imnchanearepcboo epi [sae] (Geceaan] [Dicer est wsspace Winget At pct o waking ct How to import a project 1, Select File>Import from the menu bar. 2. In the first dialog box, select the General->Existing Projects into Workspace option and click on the Next button, 3, In the second dialog box, click the Browse button and browse to the directory that contains the project you want to import. This should display the project in the Projects pane and select it. 4, Click the Finish button to import the selected project or projects. Description * To import all projects in the book_apps directory, navigate to the book_apps in step 3. This should select all projects in the book_apps directory. # Ifyou get an error that says, “Unable to resolve target”, you can fix the problem by right-clicking on the project name in the Package Explorer and selecting the Android Tools Fix Project Properties item. Figure 2. How to import an existing project, 3940 Section | Get started fast with Android How to remove a project from the workspace To keep your workspace organized, you may want to remove a project from the workspace as shown in figure 2-4, For example, if you want to remove the project named ch03_TipCalculator that's shown in figure 2-1, you can right-click on the project in the Package Explorer and select the Delete item. When you do that, you'll get a Delete Resources dialog box like the one shown in this figure. Then, you can remove the project from the workspace without deleting the files for the project by making sure that the “Delete project contents on disk” option is not selected. Or, you can remove the project from the workspace and also delete all the files associated with the project by selecting that option.Chapter 2 How to use elipse for Android development a The dialog box for removing a project from the workspace (@ vac rescues = meri rere ter recat tetera [tte prec canter on arnt beundon) Pret ctor Cachan wctapae beak ape Tiler Description * To remove a project from the workspace, right-click on the project in the Package Explorer, select the Delete item, make sure the “Delete project contents” check box is not selected, and click the OK button. # To delete a project and its directories and files, right-click on the project in the Package Explorer, select the Delete item, select the “Delete project contents” check box, and click the OK button. Then, if necessary, respond to the Delete Launch Configurations dialog box. Figure 2-4 How to remove a project from the workspace42 Section | Get started fast with Android How to work with the user interface Figure 2-5 shows how to work with the user interface. To start you can open the XML file for the user interface by expanding the res/layout directory for the project and double-clicking on the XML file for the layout, Then, if you want to view that user interface in the Graphical Layout editor, you can click on the Graphical Layout tab. In this figure, for example, the user interface for the Tip Calculator app is shown in the Graphical Layout editor. In this figure, the workbench shows the Package Explorer view, the Palette view, and the Outline view. In addition, the Properties view is shown at the bottom of the Outline view. Finally, the bottom of the workbench provides tabs that let you access more views. If a view you want to use isn’t displayed, you can display it by using the Window->Show View menu to select the view that you want. Once you've opened a user interface in the Graphical Layout editor, you can add widgets to the layout by clicking on a category in the Palette view to display the widgets for that category. Then, you can add a widget by dragging it from the Palette to the layout, and you can align a widget by dragging it to where you want it to be displayed. As you do that, the Graphical Layout editor typically displays guidelines that can help you align the widget. When you add widgets, it’s sometimes hard to find the widget you want in the Palette. In this figure, for example, it’s easy to sce that the TextView and Button widgets are available from the Form Widgets category. However, where is the EditText widget? As it turns out, several variations of an EditText widget are available from the Text Fields category, and they all have different names. Each variation is designed for accepting different types of text input, such as email addresses, phone numbers, dates, times, and numbers. To add an BditText widget that allows the user to enter a decimal number, you can use the widget named Number (Decimal). This creates an EditText widget and automatically sets its attributes so it only allows the user to enter decimal numbers. To work with an individual widget, you need to select it by clicking on it in the Graphical Layout editor or in the Outline view. Then, you can use the Properties view to set its properties. To do that, scroll through the properties for the widget and select or enter a value for any property that you want to modify. In this figure, for example, the label for the bill amount is selected, and the properties that control its alignment, are shown in the Properties view.Chapter 2 How to use elipse for Android development FS wae incase @tacaniee =| © -| #7 - S0\ o8-\ sama Description + To open the XML file for an app’s user interface, expand the res\layout directory for the project, and double-click on the file to open it. + To display a user interface in the Graphical Layout editor, click on the Graphical Layout tab, * To display a view such as the Outline view, use the Window->Show View menu. + To add widgets to the layout, click on the widget category in the Palette view to display the widget, and drag the widget onto the layout, The TextView and Button widgets are in the Form Widgets category of the Palette * All of the widgets in the Text Fields category are variations on the EditText widget. For example, the Number (Decimal) widget is an EditText widget with its proper- ties set to make it easy for the user to enter decimal numbers. * To align widgets, drag the widget within the layout. # To select a widget, click it in the Graphical Layout editor or in the Outline view. + To set the properties of a widget, select it and use the Properties view. Figure 2-5 How to work with a user interface (part 1 of 2) 4344 Section | Get started fast with Android When you develop a user interface, you often need to view its XML in an XML editor. To do that, you can open the XML file for the user interface and click on the tab that displays the name of the XML file, When you view the XML for a user interface, Eclipse makes it easier to for you to recognize the syntax by using different colors for elements and attributes. In addition, Eclipse provides standard File and Edit menus and keystroke shortcuts that let you save and edit the source code. For example, you can press Ctrl4S to save your source code, and you can use standard commands to cut, copy, and paste code. Although you can use the XML editor to create a user interface, it’s usually easier to use the Graphical Layout editor. Then, you can use the XML editor to fine-tune the user interface if necessary. As a result, you don't usually need to use the XML editor to add widgets. However, it often makes sense to use the XML editor to modify the XML that’s generated by the Graphical Layout editor: To do that, you can set the properties of a widget by adding, editing, or deleting the XML attributes for the widget. As you do this, you can take advantage of the code completion feature to enter property names and values. This feature is described later in this chapter. If you want to include comments in the XML for your user interface, you can use the code editor to add them, To do that, use the same syntax as an HTML comment (start with Description + Once the XML file for a user interface is open, you can display it in the XML editor by clicking on the tab that displays the name of the XML file. + Inthe XML editor, you can add widgets to the layout. To do that, enter the XML code for the widget. «Inthe XML editor, you can set the properties of a widget by adding or editing the XML attributes for the widget * Inthe XML editor, you can code comments. To do that, use the same syntax as an HTML comment. + When you use the XML editor, you can use the code completion feature described later in this chapter to help you enter the names and values of the properties for a widget. Figure 2-5 How to work with a user interface (part 2 of 2)46 Section | Get started fast with Android How to work with other XML resources Figure 2-6 shows how to use Eclipse to work with other XML resources besides the user interface. These resources can define display text (strings.xml), styles (styles.xml), colors (colors.xml), and so on. In this figure, for example, the strings.xml file that’s stored in the res/values directory is displayed in the XML editor. At this point, you can use the XML editor to work with this file. Or, if you want (o use the Resource editor to work with this resource, you can click on the Resources tab to display the Resource editor for this file. In most cases, though, it’s easier to use the XML editor. In general, the techniques for working with XML resources are similar to the techniques for working with the user interface. As a result, once you understand how to work with the XML for a user interface, you shouldn’t have much trouble working with other XML resources,Chapter 2 How to use Eclipse for Android development 47 The strings.xml file | omer © im en] come = Description + You can use Eclipse to work with the XML files that define display text (strings.xml), styles (styles.xml), colors (colors.xmi), and so on, + To open the XML file for a resource, expand the appropriate subdirectory of the res, directory and double-click on the XML file. © To switch to the XML editor, click on the tab that contains the name of the XML file. * To switch to the Resources editor, click on the Resources tab, Figure 2. How to work with other XML resources48 Section | Get started fast with Android How to work with the Java code ‘To work with the Java source code for an app, you can use the Package Explorer to expand the sre directory and expand the package that contains the Jjava file, Then, you can double-click on that file to open it in the Eclipse code editor. In figure 2-7, for example, the java file for the Tip Calculator activity is, open in the code editor. This file is stored in the com.murach.tipealculator pack age of the ste directory. Once you open Java code in the editor, Eclipse makes it easier for you to recognize the syntax by using different colors for different parts of the syntax, such as Java keywords, instance variables, and comments. In addition, the Outline view lists the instance variables and methods available from the current Java class, and you can jump to an instance variable or method by clicking on it You can also rename or delete a java file from the Package Explorer. To do that, just right-click on the file and select the appropriate item from the resulting menu. If you rename a file, Eclipse automatically changes both the name of the java file and the name of the class. Since the name of the .java file must match the name of the class, this is usually what you want,The Java code for the Tip Calculator app (@ me aan Bee@e BB ie: Chapter 2 Sa a @ -o-a- we. ar. vBan S Sint 4 SSitsiisttientecreny fomntioea How to use Eclipse for Android development © © Oey RR) = oa 3 Description + To display Java code in the Eclipse text editor, use the Package Explorer to expand the ste directory, expand the package that contains the Java code, and double-click Figure 2-7 oon the java file that you want, ‘To jump to an instance variable or method, you can click on the instance variable or method in Outline view. To rename a java file, right-click on the file, select the Refactor->Rename item, and enter a new name for the file. This automatically renames the class that corresponds with the file. ‘To delete a java file, right-click on the file, select the Delete item, and confirm the deletion. How to work with Java code 4950 Section | Get started fast with Android How to set the run configuration For an Android project, the run configuration specifies what Eclipse should do when you run the Android app. This includes which emulator or physical device to use. Figure 2-8 shows how to set the run configuration for an Android project. To start, you can view the run configuration for a project by right-clicking on the project in the Package Explorer and selecting the Run As->Run Configurations item from the menus. Then, to change the run configuration for the selected project, you can click on the tabs and set the options you want. In most cases, you only need to use the Target tab to set the target device for the project. In this figure, the Target tab has been set to the “Always prompt” option. That way, when you run a project, Eclipse always displays a dialog box like the one shown in the next figure that prompts you to select the emulator or physical device that you want to use. If you want Eclipse to automatically pick a device, you can select the “Automatically pick compatible device” option. Then, if a compatible physical device is connected to the computer, Eclipse will run the app on that device. Otherwise, Eclipse will run the app on a compatible emulator, If that emulator isn’t already running, Eclipse will start it.Chapter 2 How to use Eclipse for Android development 51 The Run Configurations dialog box Neve pater Aad ge Came pyr ae tctene Ss taoppenettpemie ouch onal emptied zones pomp ei Sage rere 0 hw cence eA en © Careoup ol Description * To view the run configuration for an app, right-click on the project in the Package Explorer, and select the Run As->Run Configurations item from the menus. Then, click on the tabs and set the options for the run configuration. Click the Apply button when you're done. * On the Android tab, you can specify the activity that’s started. In most cases, you can leave this tab at its default values, + On the Target tab, you can specify the device that you want to use. When testing Android apps, you often need to change the selected option on this tab. * On the Common tab, you can specify some other options for the run configuration. In most cases, you can leave this tab at its default values. Figure 2-8 How to set the run configuration52 Section | Get started fast with Android How to run an app on a physical device Figure 2-9 shows how to run an app on a connected device. To do that, make sure a compatible physical device is connected to your computer. Typically, you use a USB cable to connect your device to your computer. Then, to run an app, you can right-click on the project in the Package Explorer and select the Run ‘As Android Application item from the menus When you're working with a project, you typically set it as the current project by selecting it or one of its files in the Package Explorer. Most of the time, you do this without even realizing it. For example, when you open a file within a project, you typically select that file. Then, you can run the project for that file by pressing Ctl+F11 or by clicking on the Run button that’s available on the toolbar. Depending on your run configuration, running a project runs the app on the connected device, or it displays an Android Device Chooser dialog box like the one shown in this figure. If you get this dialog box, you can select the “Choose” option, select the device, and click the OK button. In this figure, for example, the “Choose” option would allow you to pick the physical device named “asus-nexus_7”, Once your app is running on the physical device, you can test that app using any of the hardware that’s available on that device. For example, you can rotate the device to test how it handles screen orientation changes. Similarly, if the device has a physical keyboard, you can test the physical keyboard to see if it works properly for your app. By default, Eclipse automatically compiles an app before running it. Since this saves a step in the development process, this is usually what you want. Sometimes, though, Eclipse gets confused and doesn't compile a class that’s needed by your project. For example, Eclipse sometimes doesn't compile the R class that contains the compiled resources needed by your project. In that case, you can usually fix this issue by selecting the Project>Clean item from the ‘menu bar. This cleans the project and rebuilds it from scratch. How to run an app on an emulator This figure also shows how to run an app on an emulator. To do that, you use the same technique for running an app on a physical device. However, before you run the app, you must disconnect the physical device from your computer. Or, you must set the run configuration for the project so it allows you to choose the device. Then, when you get the dialog box shown in this figure, you can select an emulator that’s already running by selecting the “Choose” option and selecting the emulator. Or, you can start a new emulator, by selecting the “Launch” option and selecting the emulator. Sometimes, an emulator may be too big to fit on your screen, Other times, the size of the emulator that’s displayed on your computer may be larger than the size of the device that you want to emulate, In those cases, you can make the emulator smaller by selecting the “Launch” option, selecting the emulator,Chapter 2 How to use elipse for Android development The Android Device Chooser dialog box (W srs Device Crooner Select device wth in Ave. Choose arming Ado device Ses Number 7 Name Tage Dawg se | Deve nen 5257005 WA van nine 1 Launch» ne Ane Vital Deice ‘vO Hime Tage time Peo aPitent crust | Baten) (Ga) | Andig42 Phen Andrei 2 7 A ame Erie sare ester te ces =D Gea) Description © Torun any app, right-click on the project in the Package Explorer and select the Run As Android Application item. This runs the app on the default device, or it displays the Android Device Chooser dialog box to let you pick the device. + To set the current project, click on the project or one of its files in the Package Explorer. To run the current project, press Ctrl+F11 or click on the Run button in the toolbar. + Torun on a physical device or on an emulator that’s already running, select the “Choose” option, select the device or emulator, and click the OK button. © To start an emulator, select the “Launch” option, select the emulator, and click the OK button. © If an emulator is too big for your screen, or if you want to emulate the actual size of a device, select the “Launch” option, select the emulator, click the Start button, and use the resulting dialog box to set the DPI and screen size. © If the Android Device Chooser dialog box doesn’t appear, you can modify your run configurations for the project as shown in the previous figure. © By default, a project is compiled automatically before it is run, which is usually what you want. * To clean and rebuild a project, select the Project->Clean item from the menu bar and respond to the resulting dialog box. Figure 2-9 How to run an app (part 1 of 2) 5354 Section | Get started fast with Android clicking the Start button, and using the resulting dialog box to set the DPI (dots per inch) and screen size. Once your app is running in an emulator, you can use the emulator to test your app. To do that, you can use your mouse to interact with the touchscreen to ‘est the app. In this figure, for example, I clicked in the bill amount text box and used the soft keyboard that was displayed to enter an amount. I also clicked on the Increase (+) button several times to increase the tip to 20%. In addition, if the keyboard and D-pad are enabled you can use your keyboard or the D-pad on the emulator to test how your app responds to the keyboards and D-pads that may be available from physical devices. When you're done testing an app in an emulator, you can leave the emulator open. That way, the next time you run the app, Eclipse won't need to boot the emulator, which takes about as much time as it does to boot a smartphone. As a result, Eclipse will be able to run your app much more quickly the next time.Chapter 2 How to use elipse for Android development The Tip Calculator app running in an emulator Cmte a @ Tip calculator Bill Amount 34.60) Percent 20% =i) ee Tip $6.92 Total $41.52 Description * Totest an app on a device, you can use any of the hardware that’s available on that device. © Totest an app in an emulator, you can use your mouse to interact with the touch- screen that’s shown on the left side of the emulator. Or, if the keyboard and D-pad are enabled you can use your keyboard or the D-pad that is shown on the right side of the emulator to emulate the hardware that’s available from some Android devices. © When you're done testing an app in an emulator, you can leave the emulator open. That way, the next time you start the app, it will start more quickly. Figure 2-9 How to run an app (part 2 of 2) 5556 Section | Get started fast with Android How to work with a new project Now that you know how to work with existing Android projects in Eclipse, you're ready to learn how to develop new Eclipse projects. Of course, many of the skills for working with existing projects also apply to working with new projects and vice versa. How to create a new project Figure 2-10 shows how to create a new Felipse project. To do that, select the File >New->Project item from the menu bar, In the resulting dialog box, expand the Android category, select the Android Application Project item, and click the Next button, This should display a New Android Application dialog box like the one in this figure, In the New Android Application dialog box, you can enter a name for the application as well as a name for the project and package. In this figure, for example, the name of the app is “Tester”, the name of the project is “Tester”, and the name of the package is com.murach.tester. Since you almost always want Eclipse to generate the code for the first activity in your app, you should make sure that the “Create activity” check box is selected as you step through these dialog boxes. Then, when the New Android Application dialog box asks you what type of activity you want to create, select the BlankActivity option. This is what you usually want, especially when you're getting started. Then, enter a name for the activity. For example, you can enter a name of “TestActivity” for the activity for this project. After that, you can click the Finish button, When you do, Eclipse creates a directory that corresponds with the project name, and it creates some additional files that it uses to config- ure the project. If you want to create a custom launcher icon for the app, you can select the “Create custom launcher icon” check box. Then, when you click the Next button, the New Android Application dialog box will prompt you to create the icon. In most eases, you can do this by selecting the Image option and browsing to the image that you want to use for the icon. If you don’t already have an image, you can often download a suitable image from the Internet. Or, if you prefer, you can skip the custom icon by deselecting the “Create custom launcher icon” check box,Chapter 2 How to-use Eclipse for Android development. 57 The New Android Application dialog box Nev Androl Appliation Crate new od Agpcaton Appian Nae Tee Project tame Teer Pacioge Nan commer Maina Rute SO 0B Ad 290) = “at s010( API An 2 ey em S Compe Wit oP And 42 Sa) = Theme d(H behtwihDokActonBar |) epactagename ar te sunqu deere yerappcabon How to create a new project 1. Select the File->New->Project item from the menu bar, 2, Select the Android Android Application Project item and click the Next button. This should display the New Android Application dialog box 3. Enter a name for the application, project, and package and click the Next button. 4, Make sure the “Create activity” option is selected and click the Next button until you reach the step that allows you to select the type for the activity, 5. Select the BlankActivity option and click the Next button. 6. Enter a name for the activity and click the Finish button Note Ifyou want to create a custom launcher icon for the app, make sure to select the “Create custom launcher icon” option in step 4, Then, the New Android Application dialog box will prompt you to create the icon. In most cases, you can do this by selecting the Image option and browsing to the image that you want to use for the icon Figure 2-10 How to create a new project58 Section | Get started fast with Android How to work with the starting code When you create a new project, Eclipse typically generates some code for you. Figure 2-11, for example, shows the code that was generated for an activity named TestActivity. Here, Eclipse generated the XML code that defines the user interface for the activity. In addition, it generated Java code that displays this user interface. If you want, you can delete or modify the generated code, The first screen shows the XML for the user interface, This XML is stored in a file named activity_test xml. Within this file, the XML defines a RelativeLayout element that’s used to organize child elements. Then, within the RelativeLayout element, a single TextView element displays a string that says “Hello world”. The second screen shows the Java code that displays the user interface, This, code defines a class named TestActivity. Within this class, the method named onCreate displays the user interface. Then, the method named onCreateOptionsMenu displays a settings menu, To practice using Eclipse, you can modify the generated code. For now, for example, you don’t need to display a settings menu, As a result, you can delete the method named onCreateOptionsMenu, Similarly, you can modify the XML code for the user interface so that the interface isn’t centered horizontally and vertically. To do that, you can use the Graphical Layout editor to change the properties of the TextView element, Or, you can use the XML editor to edit or delete the attributes named layout_centerHorizontal and layout_centerVertical of the Text View element. If you delete these attributes, the TextVView element uses its default values for these attributes, which causes the TextView element to be aligned in the top left corner of the sereen.Chapter 2 The code editor with the starting XML code for an activity Fa Ue Bw Sows Reiger feet pt Ace Wade a-wee 88 2+ E 8-O-a- Ho. ar: BH NB orn ET) pvbeerss rage =3) How to use Eclipse for Android development Han eign. Seman aman aan = > eS ane Bs 0) rong sere Soom tonto wy oe coven Somme » Description + By default, Eclipse generates some code when you create a project, but you can delete or modify this code. Figure 2. 1 How to work with the starting code60 Section | Get started fast with Android How to use the code completion feature Figure 2-12 shows how to use the code completion feature, which is also known as the Content Assist feature, to help you enter code. This feature prevents you from making typing mistakes, and it helps you enter code more quickly and easily. In this figure, for example, I am using the code completion feature to center the Java statement that sets the text for the TextView control. To do that, I entered the name of the TextView control, entered “sett”, and pressed Ctrl+Space. This displays a list of possible options. At this point, if I select the setText method from this list and press the Enter key, Eclipse will enter the name of the setText method into the code editor for me. In addition, it will automati- cally enter the opening and closing parentheses and placeholders for the argu- ments for this method. The code completion feature can also make it easy for you to enter values for string variables. If you type a quotation mark to identify a string value, the code completion feature sometimes enters both opening and closing quotation marks and places the cursor between the two. At this point, you can enter the text for the string, If you experiment with the code completion feature, you'll quickly see when it helps you enter code more quickly and when it makes sense to enter the code yourself, In addition, you'll see that it helps you understand the kinds of fields and methods that are available to the various classes and objects that you're working with, Similarly, it helps you understand the kinds of attributes that are available to the various XML elements, and the kinds of values that are available for the various attributes, If the code completion feature doesn’( work correctly on your system, it’s probably because the Content Assist feature isn’t configured correctly. To fix this issue, select the Window->Preferences item from the menu bar. Then, select the Java->Editor->Content Assist Advanced node. Finally, in the first list box, select the Java Proposals item.Chapter 2 How to use elipse for Android development The code editor with a code completion list @ neon tenon nim A aoe Fe Tae Se toes Reger far Pet ea mr = Bt BG 2: f -O-a- we- ae Se bone ER) fiverees rape Bote 7 =5) cauveu™ od | © sctestwneaientignee we iseaneanee Freee Brermersran L Berens Teter mot aheabpe| Waa | Sthaae —8 aad Description You can use the code completion feature, which is also known as the Content Assist ‘feature, to help you enter code. For Java code, this helps you enter the names of classes, objects, methods, fields, and other values. For XML, this helps you enter the names of elements, attributes, and values. To activate code completion, enter the letters you're looking for then press Cul+Space. Then, Eclipse displays a list of potential items that begin with those letters. To activate code completion for a method or field of a class or object, enter a period after a class or object name. Then, Eclipse displays a list of all the methods and fields for that class or object. You can limit these methods and fields by typing the first few letters of the method or field you want. ‘To insert an item from a completion list, use the arrow keys to select the item and then press the Enter key. Ifthe item requires parentheses, they're added automati- cally. Ifthe item requires one or more arguments, default values are added for those arguments and the first argument is highlighted so you can enter its value, Then, you can press the Tab key and enter the values for any remaining arguments If you enter the opening quote for a string value, Eclipse sometimes adds the closing quote and places the cursor between the two quotes so you can enter a value. Figure 2-12 How to use the code completion feature 6162 Section | Get started fast with Android How to detect and correct errors and warnings In Eclipse, an error is code that won't compile properly. Eclipse displays errors each time you save the source code. In figure 2-13, for example, Eclipse has displayed an error that indicates that the Text View class can’t be resolved toa type. As you can see, this single error is marked in several places in the IDE with an icon that includes a red X. In the Package Explorer, this error is marked with icons for the project directory, sre directory, package, and file that contains the source code. In addition, this error is marked in the code editor and is displayed in the Problems view To fix an error, you can jump to it by double-clicking on its message in the Problems view. This is especially helpful for projects that contain many classes or classes that have many lines of code. Once you've got the error displayed in the code editor, you can position the cursor over the error icon to read a description of the error. This is the first step in fixing the error. If the error icon includes a light bulb as it does in this figure, you can click on the error icon to display a list of possible fixes. Then, you can select the fix that you want, and Eclipse will modify your code accordingly. This is known as the Quick Fix feature. In this figure, for example, the android. widget. Text View class needs to be imported. As a result, you can fix the problem by selecting the “Import” item from the resulting menu. This adds the necessary import statement to the code, Then, when you save the file, Eclipse removes the error icons from all of its views and editors. If Eclipse doesn’t suggest any fixes, you can usually determine the cause of the error by reading the error message. Then, you can enter the fix in the code editor yourself, Felipse may also display warnings. These icons identify lines of code that will compile but may cause problems, and they are marked with a yellow triangle that has an exclamation point in it. In general, warnings work like errors, and you can use similar skills for working with them. However, there are times when you will want to ignore the warnings. If, for example, you have a good reason to use a line of code that Eclipse warns you about, you can ignore the warning. Then, if you want, you can remove the warn- ing icons from the Eclipse views by clicking on the warning icon in the code editor and selecting the “Add @Suppress Warnings” item from the resulting menu. This adds a line of code known as an annotation that prevents the warning from being displayed in the Eclipse views.The code editor with an error displayed and a possible solution Chapter 2 How to use Eclipse for Android development 63 St 85 e- f b-O-Q- were Sirereers: Co rer ag are Description Eclipse marks errors in the Package Explorer view, Outline view, and code editors with an error icon that includes a red X. Eclipse marks warnings with a yellow triangle that has an exclamation point in it, To read a description of an error or warning, you can position the cursor over the error or warning icon or you can look in the Problems view. To fix an error or warning, you can often use the Quick Fix feature. To do that, click on the icon on the left side of the code editor to display a list of possible fixes. ‘Then, select the fix that you want. You can also use the Quick Fix feature to suppress the warnings. To do that, click on the Warning icon and select the “Add @Suppress Warnings” item. Then, Eclipse will add a line of code that suppresses the warnings. Eclipse also lists all errors and warnings in the Problems view. ‘To jump to an error or a warning in the code editor, you can double-click on it in the Problems view. Figure 2-13 How to detect and correct errors and warnings64 Section | Get started fast with Android The Tester app Now that you know how to use Eclipse to create and work with an app, you're ready to gain some hands-on skills by creating a simple app named Tester that displays some text. This app is a slightly modified version of the code that's generated by Eclipse for a new project. The user interface When you run the Tester app successfully, it displays “Success!” in the upper left comer of the app as shown in figure 2-14. This may not seem like much, but creating an app like this gives you a chance to practice modifying both the XML and Java source code for an app. In addition, it’s a good test to make sure that your computer is set up and ready to begin with Android developmentChapter2 How to use Eelipse for Android development 65 The Tester app running in an emulator Success! Description + Ifitruns successfully, the Tester app displays “Success!” in the upper left comer of the screen. Figure 2-14 The user interface for the Tester app.66 Section | Get started fast with Android The XML for the user interface Figure 2-15 shows the XML code for the user interface. Most of this code was generated by Eclipse when the project was created. However, I deleted the Android attributes that centered the TextView widget horizontally and vertically. Asa result, this widget uses its default values for alignment, which aligns it in the top left comer of the screen. In addition, I added the four highlighted attri- butes to the TextView widget. The first of these attributes defines an ID for the widget. The next three attributes set the padding, text size, and text style for the widget The Java source code Figure 2-15 also shows the Java source code for the app. Again, most of this, code was generated by Eclipse when the project was created. However, I deleted the onCreateOptionMenu method that creates the options menu. As a result, this app does not display an options menu, Within the onCreate method, I added the two highlighted statements. The first statement uses the ID of the TextView widget to get a reference to that, widget. The second statement uses the set Text method to display a message of “Success!” on the TextView widget.Chapter 2 How to use elipse for Android development ity_test.xm| file xmins:teols="http://schemas.android.com/tools" "@string/helle_worla” tools:context=".Testactivity" /> The TestActivity.java file package com.murach. import android.os.Bundli import android app.Activity; import android -view.Menu; import android widget.Textviews public class TestActivity extends Activity ( eoverride public void oncreate(Bundle savedtnstancestate) ( super.onCreate(savedinstancestate); setContentView(R-layout activity test); ‘TextView message = (TextView) findViewBy1d(R.ia messageTextView); message.sotText ("Success!"); Description * The Tester app is a slightly modified version of the code that’s generated by Eclipse for a new project. In this figure, all of the highlighted code has been added to the generated code. Figure 2-15 The code for the Tester app 6768 Section | Get started fast with Android Perspective In this chapter, you learned how to use Eclipse to create and run an Android app. With that as background, you're ready to learn how to write your own Android apps. But first, I recommend that you get some hands-on practice with Eclipse by doing the exercises at the end of this chapter. Terms Integrated Development Environment workspace (DE) run configuration workbench code completion view Content Assist feature project error package Quick Fix feature code editor warning Summary + Eclipse is an Integrated Development Environment (IDE) that’s often used to develop Android apps. Eclipse is open-source, available for free, and runs on all modern operating systems. * A workspace is a directory that’s used by Eclipse to store the subdirectories and files for one or more apps. * A project is a directory that contains all of the files for an app. * In Eclipse, the workbench is where you can do most of your work. The different parts of the workbench are known as views. + The Java files for a project are typically organized into packages. Bach package has a corresponding directory in the file system. * You can use a code editor to edit XML and Java files. © Torun an application, you use a run configuration that specifies the device that the app should run on. © The Content Assist feature, which is also known as the code completion feature, helps you enter the code for XML and Java files. ‘+ Eclipse displays an error icon to mark each line of code that won't compile properly. And Eclipse displays a warning icon to mark each line of code that will compile but may cause problems You can often use the Quick Fix feature to fix errors and warnings automatically.Chapter 2 How to use Eclipse for Android development 69 Before you do the exercises for this chapter Before you do any of the exercises in this book, you need to install the JDK for Java SE, the Android SDK, Eclipse, and the ADT Plugin for Eclipse. In addi- tion, you need to create an emulator, and you need to install the source code for this book. This may take several hours, so plan accordingly. See appendix A (PC) or B (Mac) for details, Exercise 2-1 Import, run, and modify an existing app Import and run the app 1. Start Eclipse. If you haven't already done it, set the workspace to: \murach\androié\workspace 2. Within that workspace, import this project \exe_staxte\ch02_exi_vipCalculator 3. Make sure the run configuration for the Tip Calculator project always prompts you to choose the emulator or device. 4, Run the Tip Calculator app in the emulator that you created in the appendix. When you do, Eclipse should start the emulator and run the Tip Calculator within it. This may take several minutes. To display the app in the emulator, you may need to unlock the emulator by dragging the lock icon to the right. 5. Test the Tip Calculator app by using the soft keyboard to enter a bill amount and by clicking on the Increase (+) and Decrease (-) buttons to modify the tip percent, When you're done testing, don't close the emulator! 6. If you have a physical Android device, connect it to your computer and repeat steps 4 and 5 for that device. Modify the app 7. Open the java file for the activity. 8. Scroll down to the onClick method and modify it so it inereases or decreases the tip amount by 2% instead of 1%. 9. Run the Tip Calculator app in your emulator again, Note that the app displays much more quickly this time since the emulator doesn’t need to be started. 10, Test the app to make sure it’s working correctly. 11, Remove the Tip Calculator project from the Package Explorer, but don’t delete the files for the project70 Section | Get started fast with Android Exercise 2-2 Develop anew app Create the app 1 Start Eclipse. If you haven’t already done it, set the workspace for the project to this directory: \murach\android\workspa Create a project for an Android application named “Tester”. If you want, you can include a custom icon for this app. This app should be based on the BlankActivity template, and it should include an activity class named TestActivity that's stored in the com.murach ester package. Run the app in an emulator. This should display a message that says “Hello world!” in the center of the screen Modify the app 4, Introduce and correct a compil 8. Open the XML file for the user interface, Use the Graphical Layout editor to modify the user interface so it looks like the user interface for the Tester app shown in figure 2-14. Use the XML editor to view the code generated by the Graphical Layout editor. If necessary, modify this code so it works like the code shown in figure 2-15. Open the java file for the activity. Review the generated code, Add the two statements shown in figure 2-15 that set a message of “Success!”, Make sure to use code completion to help you enter these statements, Run the app in an emulator. This should display a message that says “Success!” at the top left corner of the screen. time error In the code editor for the java file, delete the import statement for the TextView class Press Ctrl+S to save the source code. code editor and the Package Explorer. ipse should display error icons in the View the error message. It should say something like “TextView cannot be resolved to a type". Us Save the file again. Eclipse should remove all error icons. the Quick Fix feature to add the import statement for the TextView class. Press Curl¥F11 to run the app. Again, this should display a message that says “Success!” at the top left commer of the screen.How to develop your first Android app In this chapter, you'll learn how to develop the Tip Calculator app that you were introduced to in the first two chapters. That will get you off to a fast start and give you the perspective you need for learning rapidly. Since you should already have some Java experience, this chapter begins by focusing on the Felipse skills that you need to develop the user interface. Then, it teaches the Java skills that you need to add functionality to that user interface. How to develop the user interface. ‘The Tip Caleulator app How to work with a layout. How to add widgets to a layout How to sot the display tet. How to work with the stings.aml file How to set properties. Common properties. ‘The XML for the user interface How to write the Java code How to work with an activity How to get references to widgets. How to handle the EditorAction event How to get and set te text for wideets. How to handle the Click event The lifecycle of an activity How to save and testore values, How to use the documentation for the Android API 108 ‘The Java code for the app no Perspective72 Section | Get started fast with Android How to develop the user interface The first step in developing an Android app is to develop the user interface. The easiest way to do this is to use the Graphical Layout editor that’s provided by Eclipse to develop most of the user interface. This generates most of the XML for the user interface. Then, if necessary, you can review and modify this code. The Tip Calculator app Figure 3-1 shows the user interface for the Tip Calculator that you'll lear how to develop in this chapter. In Android development, the components that, make up the user interface are known as widgets. Widgets can also be referred to as controls. The Tip Calculator contains ten widgets: seven TextView widgets, one EditText widget, and two Button widgets. A TextViow widget can be referred to as a text view or a label. It especially makes sense to refer to a TextView as a label when that widget provides text that labels another widget. For example, the TextView widget that displays “Bill Amount” on the left side of the Tip Calculator labels the EditText widget on the right side of the user interface. Similarly, the TextView widget that displays “Percent” labels the TextView widget that displays the value for the tip percent. ‘An EditText widget can be referred to as an editable text view or a text box. When the user touches the editable text view for the Tip Calculator, the user interface automatically displays a soft keyboard that allows the user to enter a total for the bill. After the user enters a total for the bill and touches the Done key, the app automatically calculates the tip. ‘A Button widget can be referred to as a button. In the Tip Calculator, the user can click on the Inctease (+) and Decrease (-) buttons to increase ot decrease the default tip percent. This automatically recalculates the tip.Chapter 3 How 10 develop your first Android app The user interface for the Tip Calculator oes Bill Amount 34.60, EditText widget (editable text view) Percent 18% = + Button widget (button) Tip $6.23 TextView widget (text view) Total $40.83 Soft keyboard | Description + The user interface for the Tip Calculator contains ten widgets: seven TextView widgets, onc Edit Text widget, and two Button widgets, A TextView widget can be referred to as a text view or a label, an EditText widget can be referred to an editable text view or a text box, and a Button widget can be referred to as a button ‘© When the user clicks on the editable text view for the bill amount, the user interface automatically displays a soft keyboard that allows the user to enter a total for the bill. After the user enters a total for the bill and touches the Done key, the app automatically calculates the tip. The user can click on the Increase (+) and Decrease (-) buttons to increase or decrease the default tip percent. This automatically recalculates the tip. © A widget can be referred to as a control. Figure 3-1 The user interface for the Tip Calculator app 7374 Section | Get started fast with Android How to work with a layout In Android development, a layout is a container that contains one or more child elements such as widgets and controls how they are displayed. A layout can be referred to as a form. Figure 3-2 shows the default layout of an activity, which defines a screen. An activity like this one is created automatically when you create a new Android project that’s based on the BlankActivity template as described in the previous chapter. Android provides several different types of layouts. In chapter 5, you'll learn more about working with different types of layouts. For now, you’ll learn how to use the relative layout to create the interface for the Tip Calculator app. In. this figure, the relative layout contains a single TextView widget that displays a message of “Hello world!”. Since a new project typically generates at least one layout file for you, you can usually begin by opening an existing layout. To do that, expand the project, in the Package Explorer, expand the res (resources) directory, expand the layout directory, and double-click on the name of the XML file. Once you've opened a layout, you can view it in the Graphical Layout editor by clicking on the Graphical Layout tab. Then, you can use the techniques described in the next few figures to add widgets to the layout, to align those widgets, and to set their properties. Then, if you want to review or edit the XML code that’s generated for the layout, you can click on the tab that displays the filename of the layout. If you need to change the type of layout, you can do that by right-clicking on the layout in the Outline window, selecting the Change Layout item, and selecting the type of layout. For example, if you're working with another type of layout such as a linear layout, you can use this technique (o change it to a relative layout. Then, you can use the skills described in this chapter to create the user interface Similarly, when you need to add additional layouts to a project, you can do that by right-clicking on the project in the Package Explorer and selecting the New- Android XML File item. Then, you can enter the name of the file and select the type of layout, For now, select the relative layout. Conversely, if you want to delete a layout from a project, you can do that by right-clicking on the layout in the Package Explorer, selecting the Delete command, and clicking the OK buttonChapter 3 How to develop your first Android app = 75: The default layout for an activity in a new project (9 nn ptaatevemsiny isan 101 ———— He (Se nagar See Pet ee Wnt Hp 1 . 82 Grd eO-a+ wor Be. SB omy TR 5 aa aes — rae | | Beem =| B=] Heep - Stomp | icine | @ >) aa aagag Drennepaece 1 pean Description * By default, a new Android application includes a layout file that uses a relative layout and a single Text View widget that displays “Hello world)”. + To open an existing layout, expand the project in the Package Explorer, expand the res (resources) directory, expand the layout directory, and double-click on the name of the XML file. To change the type of layout, right-click on the layout in the Outline view, select the Change Layout command, and select the type of layout, ‘* To create a new layout, right-click on project in the Package Explorer and select the New->Android XML File item. Then, enter the name of the file and select the type of layout. For now, select relative layout + To delete a layout, right-click on the layout in the Package Explorer, select the Delete command, and click the OK button. + To view the layout in Graphical Layout editor, click on the Graphical Layout tab. ‘+ To viow the layout in XML view, click on the tab that displays the filename of the layout Figure 3-2 How to work with a layout76 Section | Get started fast with Android How to add widgets to a layout Figure 3-3 shows how to add widgets to a layout. To do that, you just drag a widget from the Palette onto the layout. This figure, for example, shows the ten widgets for the Tip Calculator after they have been added to the layout but before all of their properties have been set correctly. The Palette has several ways of displaying widgets. In this figure, I have displayed an icon and text for each widget, To do that, I right-clicked within the Palette and selected the “Show Icon and Text” item. However, if you prefer, you can display previews of the widgets by right-clicking within the Palette and selecting one of the “Preview” items. As you add widgets to a layout, you often need to switch categories in the Palette so you can find the widget you want to add, To do that, you can click on the category for the widget. The Form Widgets category contains a variety of useful widgets including the TextView and Button widgets. The Text Fields category, on the other hand, only contains variations of the EditText widget, For this figure, I used the widget named Number (Decimal). When you use the relative layout, it’s a good practice to set the Id property for the widget as soon as you add it to the layout. That way, the other widgets can use that ID to align themselves relative to this widget. In this figure, for example, I set the Id property of the last Text View widget to @+id/otalText View. Here, the prefix of @-+id/ identifies the following text as the ID. As a result, the ID of the widget is totalTextView. This clearly indicates that this widget is a TextView widget for the total amount, If you modify the Id property for a widget after you have aligned other widgets relative to that widget, Eclipse might not be able to align your widgets correctly. To fix that, you need (o update all references to the Id property that you modified. An easy way to do that is to switch to the XML editor and use the Find/Replace feature. By default, the Properties view is displayed below the Outline view. If it isn’t there, you can display it by selecting the Window Show View Other item from the menus. Then in the resulting dialog box, you can expand the General category and select the Properties item, In most cases, you can align a widget by dragging it to where you want it to be aligned. This sets properties of the widget in the Layout Parameters group such as the Align Baseline property, the Align Left property, and so on. In this figure, for example, the Properties view shows some of these properties for the selected TextView widget After you add widgets, you may need to delete one or mote of them. To do that, click on the widget in the Outline view and press the Delete key. If you delete it in the Graphical Layout editor, it might not be deleted correctly. As you add widgets to a layout, you may need to set its theme, which is a group of styles that define the look of the layout. To set the theme, select it from the toolbar that’s displayed above the Graphical Layout editor. In this figure, the AppTheme has been selected, which is usually what you want when you're getting started. You'll learn more about working with themes in chapter 7.Chapter 3 How 10 develop your first Android app A layout after some widgets have been added to it (9 mo oan ieoannrenenay eames TL eS ae ee tga eet Pape Wo ep “ao AG ed b-O-a Bor OF. SO ED Some 5 |: Temes [ei| aa ones] “ee aaa “Ta - —— Brewanatn i Bcc ra I Bemwrerme euticy tev ton (Bitton ‘grhoet Et caleee Description To add a widget, click on the category for the widget in the Palette view and drag the widget from the Palette onto the layout. TextView and Button widgets are in the Form Widgets category, and EditText widgets are in the Text Fields category. To display the icon and text for a widget in the Palette, right-click within the Palette and select the “Show Icon and Text” item. When you use the relative layout, it’s a good practice to set the Id property for the widget as soon as you add it to the layout. To do that, you can click on the widget and use the Properties view to set the Id property. By default, the Properties view is displayed below the Outline view. If it isn’t there, you can display it by selecting the Window Show View-> Other item from the ‘menus, expanding the General category, and selecting the Properties item. To align a widget, you can drag it to where you want it to be aligned. This sets properties of the widget in the Layout Parameters group such as the Align Baseline property, the Align Left property, and so on. To delete a widget, click on the widget in the Outline view and press the Delete key. If you delete it in the Graphical Layout editor, this might not work correctly, A theme is a group of styles that define the look of the layout. To set the theme for the layout, select the theme from the toolbar. Figure 3-3 How add widgets to a layout 7Section | Get started fast with Android How to set the display text ‘The Android development environment encourages separating the display text from the rest of the user interface. The advantage of this approach is that it's casier to ereate international apps that work in multiple languages. The disadvan- tage is that it takes a little extra work to set the display text for the user interface. However, figure 3-4 shows a technique that makes it easy to set the display (ext, and this extra step shouldn't slow down your development much once you get used to it, In this figure, for example, I set the Text property for the first Text View widget to a string named bill_amount_abel that’s stored in the strings xm file, This is indicated by the value for the Text property which is set to: @atring/bi1i_amount_label This string contains a value of “Bill Amount”, and this value is displayed in the Graphical Layout editor.Chapter 3 How to develop your first Android app 79 82 a gd e-O-a- we BF Se Ooo ED Soa e235) urgonng— 34.60. recerd 188 rar rn xeon come 31 How to set the text property for a widget 1. In the Graphical Layout editor, select the widget. 2. In the Properties view, click the button (...) to the right of the Text property. 3. In the Resource Chooser dialog box, click the New String button to add a new string. Or, if the string is already available, select the string and click the OK button, 4, In the Create New Android String dialog box, enter a name and value for the string and click the OK button, Description + Ie’s generally considered a best practice to store the display text for your app in a separate XML file. This makes it easy to internationalize your application, Figure 3- How to set the display text for a widget (part 1 of 2)80 Section | Get started fast with Android After you click the button (...) to the right of the Text property, Eclipse displays the Resource Chooser dialog box. If the string you want to display is available from this dialog box, you can select it and click the OK button. This sets the display text to the selected string. On the other hand, if you need to enter a new string, you can click on the New String button to display the Create New Android String dialog box. Then, you can enter the string you want to display and a name for the string, In this figure, for example, I entered a string of “Bill Amount” with a name of bill_amount_label. When you click the OK button, Eclipse displays the Resource Chooser dialog box with the string you just created. As a result, you can click the OK button to set the display text to your newly created string,Chapter 3 How to develop your first Android app 81 The Resource Chooser dialog box Rewcafie ahaleal geo Options apace al fies apace nal 0 estore canton Figure 3-4 How to set the display text for a widget (part 2 of 2)82 Section | Get started fast with Android How to work with the strings.xml file When you use the technique shown in the previous figure to set the display text for your app, Eclipse stores the text in a strings.xml file like the one that's shown in figure 3-5. If you want, you can open the strings.xml file and edit it just as you would edit any other XML file. This figure shows the strings.xml file for the Tip Calculator app. Here, the first two strings are used in the manifest file to identify the name of the app and the name of the main activity of the app. Both of these strings are set to “Tip Calculator” ‘The third string is for a Settings item in the options menu. Since this app doesn’t display an options menu, this string isn’t displayed anywhere in the app. However, since this string is referred to by the unused options menu, deleting this string causes an error that prevents the project from compiling. As a result, I decided to leave this string and the unused menu in the project for now. The last ten strings are used for the widgets. The strings that provide labels for widgets have names that end with “label”. Other strings provide default values for the bill amount, tip percent, tip amount, and total. These default values make it easier to use the Graphical Layout editor to set the properties for the widgets that display these values. In addition, they can make it easier to test an app. For example, when the app starts, it displays a value of 34.60 in the editable text view for the bill amount, As a result, you don’t have to enter a bill amount to test the app. However, before you put the app into production, you can modify the app so it sets these values to appropriate starting values for the app. For example, you probably want to supply an empty string for the bill amount. That way, when the app starts, the editable text view for the bill amount will be blank If you want to supply a strings.xml file for another country, you can create a values-xx directory within the res directory where xx is the ISO two-letter code for the country. For example, fr is the two-letter country code for France. Then, you can supply a strings xml file within that directory that uses French instead of English. To find a list of these two-letter codes, you can search the Internet for “ISO two-letter country code”Chapter 3. Howto develop your first Android app 88 The location of the strings.xml file res/valu: strings.xml The strings.xml file for the Tip Calculator app
Tip Caloulater
settingac/atring>
Bill Amount bill _amount">34.60
Percent
15%
+
~
Tip
$0.00
abel">Total
$0.00 The location of a strings.xml file for France res/valus fx/strings.xml Description ‘+ When you use the technique shown in the previous figure to set the display text, for your app, Eclipse stores the text in the strings.xml file that’s shown in the next figure. Ifyou want, you can open the strings.xml file and edit it just as you would edit any XML file * To provide a strings.xml file for a country that uses another language, you can create a values-xx directory within the res directory to store the strings.xml file. Here, you can replace xx with the ISO two-letter country code. Figure 3-5 How to work with the strings xm file84 Section | Get started fast with Android How to set properties Figure 3-6 shows how to use the Properties view in the Graphical Layout editor to set the properties of a widget. To do that, select the widget and use the Properties view to change the property. After you change a property from its, default value, the Properties view displays the property in white. In this figure, for example, the Properties view shows that the Text Style property has been set to bold,Chapter 3 How 10 develop your first Android app A layout after some properties of the widgets have been set (nm. oa ecanr ec Fe (oe Rescate Sch Pet Wnton Hep St 8B Gr SeO-a- wor BF- \ wom ETE fee el ee LE femmes | gar - — Stem | —Bilapaung- 3460. Percent 15% + Tip 0.00 Total $0.00 1 rors ute Eton ie 17 in Description + To set a property for a widget, select the widget and use the Properties view to change the property. + The properties that have been changed from their default are displayed in white in the Properties view. Figure 3. How to set properties86 Section | Get started fast with Android Common properties Figure 3-7 shows the properties that are used by the Tip Calculator app. These properties are commonly used by most apps. As a result, you should review them and make sure you understand how they work, Fora layout, the Width and Height properties are typically set to a pre-defined value of “match_parent”. This expands the layout so it takes up the entire parent minus padding. In most cases, this causes the layout to take up the entire screen. You may sometimes see a value of “fill_parent” instead of “match_parent”. These values work the same, but “fill_parent” has been depre- cated and replaced by “match_parent” as of Android 2.2 (API Level 8). For the Tip Calculator app, the Padding property of the layout is set to a value of “10dp". As a result, the layout includes 10 density-independent pivels (dp) of space between the edge of the screen and the widgets contained by the layout. Although Android supports other units of measurement such as inches, it’s a best practice to use density-independent pixels whenever possible. When you use a relative layout, it’s considered a best practice to specify the Id property for each widget. To do that, you begin the value of the Id property with a prefix of @+id/, This indicates that you are specifying an ID value for the widget. Then, you can specify the ID for the widget. In this figure, the Id prop- erty shows how to set the ID for a widget to bill AmountLabel. For a widget, the Width and Height properties are typically set to a predefined value of “wrap_content”. This forces the width and height to be just big enough to contain the widget and its content. However, if you want, you can use density-independent pixels (dp) to specify the height or width of a widget. For the Text property, you begin with a prefix of @string/. This indicates that you are specifying a value that’s stored in the strings.xml file. In this figure, the Text property shows how to set the display text for the widget to the string in the strings.xml file that’s named bill_amount_label. For the Text Size property, it's generally considered a best practice to use scale-independent pixels (sp) whenever possible. In this figure, the Text Size property specifies a value of “20sp”. This indicates that the text size should be 20 scale-independent pixels tall. The last two properties are typically used with an EditText widget. Here, the Ems property sets the width of the FditText widget so it’s wide enough to contain the specified number of the letter m. The Input Type property sets the type of input that the EditText widget should accept. In this figure, for example, the Input Type property specifies a value of “numberDecimal”. This indicates that the EditText widget should only accept characters for decimal numbers. In other words, it should only accept numeric characters and the decimal point character. Of course, the numberDecimal value is only one of the many values that specify the types of input that an EditText widget can accept. For example, an EditText widget can accept plain text, email addresses, telephone numbers, passwords, and so on, In chapter 5, you’ll learn more about how to specify the type of input for an EditText widget.Chapter 3 How 10 develop your first Android app Common properties for layouts Gono mec een width match_parent, Height match_parent Padding 104 Common properties for widgets Rood Example settings ry @+ia/bi11Amounttabel width weap_content Height weap_content Align Parent Left true Align Parent Top true Padding 10a Text @string/bill_anount_label Text Size 208p Text Style bola Margin Left 1304p Ems a Input Type numberDecimal weap_content Wraps the height or width so itis large enough to display the widget. match_parent Stretches the height or width to match the parent container. All_parent Replaced by match_parent, Deprecated starting in API Level 8, Common units of measurement CE ce ed Density-independent pixels dp or dip ‘margins, padding, ete Scalesindependent pixels sp font sizes Description + For the Id property, you begin with a prefix of @-4id/ to indicate that you are specifying an ID value for the widget. + For the Text property, you begin with a prefix of @string/ to indicate that you are specifying a value that’s stored in the strings.xml file. * Although Android supports other units of measurement, such as inches, it’s a best practice to use density-independent and scale-independent pixels whenever possible. Figure 3-7 Common properties 8788 Section | Get started fast with Android To specify a density-independent pixel, it's possible to use an abbreviation of dip instead of dp. For example, you could use “10dip” instead of “10dp”. In this book, Iuse dp for two reasons, First, it's shorter. Second, it’s more consistent with the sp abbreviation that’s used for scale-independent pixels. The XML for the user interface Figure 3-8 shows the XML for the user interface. This code is stored in the file named activity_tip_calculator.xml fil. The code in this figure is the same as the XML code presented in chapter 1 By now, though, you should understand how to use the Graphical Layout editor to generate this kind of code, you should understand how to use the XML editor to work with this code, and you should understand the details of how this code works. One main point to notice is that the layout attributes align these widgets relative to one another. These attributes begin with a prefix of “layout” To start, the RelativeLayout element defines a relative layout that contains the widgets for the user interface. Here, the first two attributes for the layout are set automatically, and you can usually ignore them. Then, the layout_width and layout_height attributes use a value of match_parent to specify that the layout should use the whole screen. Finally, the padding attribute determines that there should be 10dp of space between the edge of the layout and its child elements, The first TextView clement displays “Bill Amount” on the user interface. The first attribute of this widget defines an ID of billAmountLabel for the widget. The next three attributes for this widget set its width, height, and padding. Here, the width and height attributes use a value of wrap_content to specify that the widget should be just wide enough and tall enough to fit its content. The fifth attribute sets the text that’s displayed on the widget to the value that’s stored in the bill_amount string of the strings.xml file. The sixth attribute sets the size of the text to 20 scale-independent pixels (20sp). Finally, the last attribute sets the style of the text to bold. The EditText element displays the widget that allows the user (o enter a bill amount. By now, you should understand how most of the attributes of the EditText clement work. Within a relative layout, the alignment attributes align the editable text view relative to other widgets. In this case, the alignment attributes align the editable text view to the right of the TextView element for the bill amount label with a margin of Sdp between the two elements, Also, the ems attribute specifies that the editable text view should be wide enough to fit 8 ems (8 of the letter m). And the inputType element specifies that the soft keyboard should only allow the user to enter decimal numbers, The next two TextView elements define the widgets that display the tip percent. The Button elements define the buttons that allow the user to increase or decrease the tip percent. These widgets are square (45dp x 45dp), And the last four TextView elements define the widgets that display the tip and total amounts,Chapter 3 How 10 develop your first Android app The XML for the user interface Page 1 ‘nt tp: //schenas-android.con/apk/res/androia” watch_parent™ ayout_height="match parent" android:padding="10ap" >
The tip percent
Figure 3-8 The XML for the user interface (part 1 of 3)90 Section 1 Get started fast with Android The XML for the user interface Figure 3-8
The XML for the user interface (part 2 of 3) Page 2Chapter 3 How to develop your first Android app 1 The XML for the user interface Page 3
android:id="@+id/totalrextview" android:layout_width="wrap_content™ android:layout_height="wrap_content" android: layout_alignBaseline="@+id/totalLabel* Description © The activity_tip_calculator.xml file contains the XML that defines the user interface. Figure 3-8 The XML for the user interface (part 3 of 3)92 Section | Get started fast with Android How to write the Java code Once you have the user interface working the way you want, you can write the Java code for the app. This is the code that provides the functionality for the app, How to work with an activity Figure 3-9 shows how to work with an activity. When you create an Android project based on the BlankActivity template, Eclipse automatically creates a class like the one shown in this figure. This class inherits the Activity class and overrides the onCreate method of that class. Android runs this method when the activity is started, Within the onCreate method, the first statement passes the Bundle param- eter to the onCreate method of the superclass (the Activity class). Then, the second statement displays the user interface for the activity. To do that, it calls the setContent View method of the superclass. Within the parentheses for this method, the code specifies the resource for the layout. To do that, this code uses the R (resources) class. The R class is created automatically when you build your project, and it provides a way to access the compiled resources for your project. In the onCreate method, for example, this cade: R.layout.activity tip_calculator refers to a compiled version of this resource: res\layout\activity tip_calculator.xnl By default, the activity class includes an onCreateOptionsMenu method that displays an options menu. If your app doesn't need an options menu, you can delete this method. If your app needs menus, you can learn more about working with them in chapter 7 If you're creating an app like Tip Calculator that only uses a single activity, you can usually modify the generated class to get it to work the way you want. However, if you need to add an additional screen to your app, you need to add a new activity, To do that, you can right-click on the project name in the Package Explorer, select the New-> Other item. Then, expand the Android category, select, the Android Activity item, and respond to the resulting dialog box. This adds an XML file for the user interface as well as a Java file that defines a class that inherits the Activity class that’s similar to the one shown in this figure.Chapter 3 How to develop your first Android app 9B. The default Java code for an activity package com.murach.tipcalculater; import import android.app.Activity; import android -view.Menu; public class TipCalculatorActivity extends Activity ( Goverriae public void oncreate(Bundle savedInstancestate) ( super.onCreate (savedinstancestate) jet Content View(R-layout.activity tip_ealculater); > Goverride public boolean onCreateoptionsMenu(Menu menu) ( jetMenuInflater().inflate(R.menu.activity tip_caleulater, menu) return true; Description © When you create an Android project that’s based on the BlankActivity template, it automatically creates a class for the fist activity in your app. This class displays the user interface for the activity. * To create a new activity, you can right-click on the project name in the Package Explorer, select the New->Other item, Then, expand the Android category, select the Android Activity item, and respond to the resulting dialog box. Android runs the onCreate method when the activity is started. + The onCreate method usually passes the Bundle parameter to the onCreate method of the superclass. + The onCreate method usually uses the setContentView method of the Activity class to specify the resource for the layout. * The R class provides a way to access the compiled resources for your project. This class is created automatically when you build your project. * Android runs the onCreateOptionsMenu method when it’s ready to display the options menu. © To remove the options menu from an app, delete the onCreateOptionsMenu method, Figure 3-9 How to work with an activity94 Section | Get started fast with Android How to get references to widgets ‘The previous figure shows the starting Java code for displaying a user inter- face, Now, figure 3-10 shows how to get references to the widgets on the user interface, This is the first step to adding functionality to a user interface. To make it easy to work with widgets, you typically start by adding import statements that import the classes for the widgets. Most widgets are stored in the android. widgets package. In this figure, for example, the Text View and EditText classes are both stored in this package. After you import the classes for the widgets, you typically declare the widgets as private instance variables of the activity. In this figure, for example, three widgets have been declared as private instance variables. Here, the first widget is an EditText widget, and the other two are TextView widgets. In the onCreate method, you can use the find ViewByld method to get refer- ences to the widgets that are declared in the layout. To do that, you can use the R (resources) class to access compiled resources. In this figure, for example, the first findViewByld method specifies an argument of: R.id-billAmounteditrext. This gets a reference to a compiled resource with an ID of billAmountEditText. If you look at the XML file for the user interface, you'll find that this ID corresponds with the ID of the EditText widget on the user interface. Similarly, the other two IDs specified in this figure correspond with the IDs of two of the Text View widgets. The find ViewByld method returns a View object that can be cast to the correct type for each widget. In this figure, for instance, the first statement casts the View object for the bill amount to the EditText type. Then, the next two statements cast the View object that's returned to the TextView types. This works because the View class is the superclass for all widgetsAn acti packas import Chapter 3 How to develop your frst Android app 95. ity that gets references to the widgets com-nurach.tipcalculater; import android.widget.zaitrext; ///1, Import the Classes for the widgets import android widget .TextView; import android app.Activity; public class Tipcalculatoractivity extends Activity ( 17 2. Declare variables for the widgets private EditText billancuntEditrext; private TextView tipTextView; private TextView totalTextView: Goverride public void oncr jundle savedinstancestate) ( super.onCreate (savedinstancestate! Content View(R-layout activity tip calculator); 11 3. Get references to the widgets billanountuditrext = (EditText) fndViewByzd(R.id billamountEditrext); tipextView = (TextView) findViewByrd(R.id.tipTextview); totaltextView = (TextView) findViewsyrd(R.id.totalTextView); Description You can add import statements to import the classes for the widgets from the android. widgets package. You can declare widgets as private instance variables of the activity. You can use the find ViewByld method to get references to the widgets that are declared in the layout The findViewByld method accepts an argument for the ID of the widget. The R class provides a way to get the ID for any of the compiled resources for your project The findViewB yId method returns a View object for the widget with the specified ID. This View object can be cast to the correct type of the widget. Figure 3-10 How to get references to the widgets96 Section | Get started fast with Android How to handle the EditorAction event Now that you have references to some of the widgets on the user interface, you're ready to learn how to code an event handler. An event handler is a special type of method that's executed when an event occurs. Typically, an event occurs when a user interacts with widgets. In figure 3-11, for example, you'll learn how to handle the EditorAction event. This event typically occurs when a user interacts with the EditText widget to display a soft keyboard and presses an action key such as the Done key. In general, there are three steps to handling an event. First, you need to import the interface that defines a listener, which is an object that listens for an event. In this figure, the sixth import statement imports the OnBditorActionListener interface. Second, you need to create a listener. To do that, you can implement the listener interface. In this figure, the class declares that it implements the OnEditorActionListener interface, and then it implements the method that’s defined by the interface: the onEditorAction method. This method contains the code that’s executed when the listener detects that an action event occurred on the widget Third, you must connect, or wire, the listener to a widget. In this figure, the last statement in the onCreate method wires the EditText widget for the bill amount to the onEditorAction listener that’s defined by the current class. To do that, this code calls the setOnEditorActionListener method from the EditText widget for the bill amount, Then, it uses the keyword named this (o pass the object for the current class to that method. When you're implementing interfaces, Eclipse can automatically generate the method or methods defined by the interface for you, which is usually what you want. To do that, you can code the implements keyword followed by the name of the interface. Then, you can click on the error icon that Eclipse displays (o the left of this code and select the “Add unimplemented methods” item. When you do, Eclipse generates the method or methods for you. If necessary, you can modify the names of the arguments. In this figure, for example, I changed the default names of the arguments to make them more readable. Within the onEditorAction method, you can handle the events that occur on specific action keys such as the Done key by comparing the second parameter (the ID of the action key) with the constants of the EditorInfo class. In this figure, this method begins by checking whether the Done button was clicked or whether an unspecified action occured such as an Enter key being pressed on an older device. If either condition is true, this code sets the tip to $10 and the amount to $110. If not, the tip and amount are left at their default values. Bither way, this method returns a false value, which causes the soft keyboard to be hidden, which is usually what you want. If you review the onEditorAction method, you'll notice that the first and third parameters aren't used in this code, That’s because the first parameter is used to determine which widget triggered the event. For this code, there is only one widget that has been wired to the event, so that widget is the only oneAn act Chapter 3. Howto develop your first Android app 97 ivity that handles the EditorAction event package com.murach.tipcalculator; import import import import import import import public android view.KeyEvent; android view. inputmethod.zditorInfo; android widget .Eaitrext: android widget .textView; android widget TextView.onzditorActionListener; // 1: Import List android. app.Activity; class TipcalculatorActivity extends Activity implements OnEditorActionListener ( // 2a. Implementthe) listens: private Editvext billamcuntEditrext; private TextView tiprextView, private TextView totalvextView; Goverride public void oncreate(Bundle savedinstancestate) ( > super.onCreate(savedinstancestate); setContentView(R.layout activity tip_calculator); billamountEaitrext = (p4itText) fndViewByzd(R.id-billamountEditext); tiprentview = (TextView) findViewsyrd(R.id.tiprextview); totaltextView = (TextView) findViewById(R.id-totalTextView); 1/3. Set the lis billamountEditvext. stOnEditorActionListener (this); 17 2». Implement the listener Goverriae public boolean onkditerAction(TextView v, int actionId, KeyEvent event) ( if (actionId == Eaitorinfo.IME_ACTION_DONE || actionIa == EaitorInfo.IME_ACTION_UNSPECIFIED ciptextview.setTent ("$10.00"); totalTextView.setText ("$110.00"); > return false; Description * Anevent handler is a special type of method that’s executed when an event occurs. Typically, an event occurs when a user interacts with widgets, * A listener is an object that listens for an eve nt. To create a listener, import the interface for the listener and implement that interface. After you create a listener, connect, or wire, the listener to an event that’s available from a widget The EditorAction event typically occurs when the user uses a soft keyboard to enter text into an editable text view. Figure 3-11 How to handle the EditorAction event (part 1 of 2)98 Section | Get started fast with Android that could possibly trigger the event. The third parameter, on the other hand, is used to determine whether the Enter key triggered the event. For now, this app assumes that the device is a touchscreen device that doesn’t have a physical Enter key. As a result, this app doesn’t handle the Enter key. Part 2 of figure 3-11 shows a few of the constants that are available from the EditorInfo class. All of these constants begin with IME, which stands for input method editor. An input method editor (IME) is a user control such as a soft keyboard that enables users to input data, often (ext The first constant shown in this figure is used in part 1 of this figure to check whether the Done key was pressed. The next three constants can be used to check for the Go, Next, and Search keys. Although these keys aren’t available from the soft keyboard for the Tip Calculator shown in this chapter, they are available from other types of soft keyboards. For example, the Go key is avail- able from the soft keyboard for entering a URL. Finally, the last constant can be used to check for an unspecified action such as an Enter key that’s available from an older device. ‘As you review this code, you should be aware that there are several possible ways to define a class that implements the interface for a listener. In this figure, I decided to use the class for the activity to implement this interface. That way, that class defines the activity, and it acts as the listener for the EditorAction event, However, in some cases, it makes sense to define a separate class for the listener. You'll learn more about how this works in chapter 6.Chapter 3 How 10 develop your first Android app 99 A few constants from the Editorinfo class The action key performs... IME_ACTION_DONE A “done” operation, typically closing the soft keyboard, IME_ACTION_¢o A “go” operation, typically taking the user to the target specified by the user. IME_ACTION_NExT A “next” operation, typically taking the user to the next field that needs text input. IME_ACTION_SEARCE ‘A “search” operation, typically searching for the text specified by the user. IME_ACTION_UNSPECIFIED No specified operation, typically an action key on an older device such as an “enter” key. Description * After you declare the interface for the listener, you can automatically generate the declaration for the method by clicking on the error icon and selecting the "Add unimplemented methods” item. * An input method editor (IME) is a user control such as a soft keyboard that enables users to input data, often text. + To determine which widget triggered the event, you can use the first argument of the onEditorAction method. + To determine which action key triggered the event, you can use the second argu- ‘ment of the onEditorAction method. To do that, compare the second argument with the constants of the EditorInfo class. * To determine whether the action was trigged by pressing the Enter key, you can use the third argument of the onEditorAction method. * To hide the soft keyboard, you can return a false value from the onBditorAction method. To keep the soft keyboard displayed, you can return a true value from the onEditorAction method. Figure 3-11 How to handle the EditorAction event (part 2 of 2)100 Section 1 Get started fast with Android How to get and set the text for widgets Figure 3-12 shows how to get and set the text that’s displayed on a widget. Typically, you need to get the text from widgets such as editable text views that allow the user to enter text. Conversely, you often need to set the text on widgets, that display text such as labels. However, these techniques work for most types of widgets, You can use the getText method to get the text that’s displayed on a widget, To do that, you call the getText method from the widget. This returns an Editable object. In most cases, you want to call the toString method from the Editable object to convert it to a String object. In this figure, for instance, the first exam- ple gets the text from the editable text view for the bill amount and converts that text to a string. You can use the setText method to set the text that’s displayed on a widget. To do that, you call the setText method from the widget and you pass a string argument that contains the display text. In this figure, for instance, the second example sets the display text for the TextView widget to “Test 1”. The calculateAndDisplay method shown in this figure uses both the getText, and setText methods, To start, the first statement gets the display text from the editable text view for the bill amount and converts that text to a string. Then, this, code uses the parseFloat method of the Float class to convert that string to a float value, Since the editable text view for the bill amount only allows the user to enter an empty string or a string for a decimal number, this code doesn't include a try statement that handles the exception that occurs if the user enters non-numeric data, However, this code does use an if statement to convert an. empty string to a zero, ‘Alter getting a float value for the bill amount, this code calculates the tip and total amount for the bill. Here, the code assumes that the tip is a float value of 15%, and it uses the float type for all of these variables. To specify the literal value for the tip percent, this code appends an f to the number (o indicate that it is a float value, Before this code can display the tip and total amounts, it must convert them to string values. To do that, this code uses the NumberFormat class. First, it calls the static getCurrencylnstance method of the NumberFormat class to return a NumberFormat object for curreney formatting, Then, it uses the format method of the NumberFormat object to convert numeric values to strings that have currency formatting, and it displays these strings on the TextView widgets for the tip and total amounts. Although the code in this figure shows how to work with float values, you can use a similar technique to work with double and integer values. For example, you can use the parselnt method of the Integer class to convert a string to an int value Although the code in this figure shows how to work with curreney format- ting, you can use a similar technique to work with percent formatting. In particu- lar, you can use the static getPercentInstance method of the NumberFormat class to return a NumberFormat object that you can use to convert numbers to strings that have percent formatting.Chapter 3 How to develop your first Android app 101 Two methods for working with widgets Poca gettext () Returns an Editable object that represents the text that the widget is displaying. You can use the toString method to convert the Editable object to a string. set Text (st: Sets the text that’s displayed on the widget. Examples How to get text String billAnountstring = billAmountEditText.getText().tostring(); How to set text tiprextview.setText (™ 1"); A method that gets input, calculates amounts, and public void calculateandDisplay() ( plays output WJ get the bill amount billamountstring = billAmountEditText.getText ().tostring(); fost billamount; if (billamountstring billAmount = 0; equals(")) ¢ « billamount = Float parseFloat (billAnountstring)? > J] calculate tip and total float tipPercent = .151 float tipAmount = billAmount * tipPercent; float totalamount = billAmount + tipAmount; W/ @isplay the results with formatting MumbezFormat currency = NumberFormat .getCurrencytnstance(); tiprentView. set Text (currency. format (tipAmount)); totalTextView.setText (currency.format (totalAmount)); Description «For most widgets, you can use the getText and setText methods to get and set the text that’s displayed on the widget. + Ifnecessary, you can use the Integer, Double, and Float classes to convert the strings that are returned by widgets to int, double, and float values. + Ifnecessary, you can use the NumberFormat class to convert numeric values to string values that have currency or percent formatting so they can be displayed on widgets Figure 3-12 How to get and set the text for widgets102 Section | Get started fast with Android How to handle the Click event Figure 3-13 shows how to handle the Click event. This event is available from most widgets, but it's almost always handled for buttons, which are designed to be clicked. The steps for handling the Click event are the same as the steps for handling the EditorAction event that you saw earlier in this chapter. First, you import the interface for the listener. Often, Eclipse does this for you automatically when you declare the interface. As a result, you can often skip this step. Second, you implement the interface by declaring it and by implement- ing any methods declared by the interface. In this figure, the class for the Tip Calculator activity declares that it implements the OnClickListener interface, and it includes the onClick method that’s defined by this interface. Third, you wire the listener to a widget. In this figure, the two statements, wire the event handler shown in this figure to both of the buttons on the Tip Calculator app. To do that, this code calls the setOnClickListener method from each button and passes the object for the current class to that method, Since the onClick method is wired to two buttons, the code in the onClick method includes a switch statement that checks which button was clicked and executes the appropriate code. To do that, the switch statement gets the ID of the widget by calling the getId method from the View object that’s the first and only argument of the onClick method. Then, it compares this value to the IDs of the Button widgets. To get these IDs, this code uses the R class to access informa- tion about the compiled resources for the project, For instance, to get the ID for button named percentDownButton, it uses this code: R.id.percentDownButton Earlier in this chapter, the onEditorAction method didn’t need to include code like this because that event handler was only wired to a single widget Since a class can implement multiple interfaces, a class can handle multiple events, In this figure, for instance, step 2a shows that the class implements both the OnClickListener and OnEditorctionListener interfaces.Chapter 3 How to develop your first Android app 103, How to handle the Click event Step 1: Import the interface for the listener Amport android view.View.onClickiistener; Step 2a: Implement the interface for the listener public class Tipcalculatoractivity extends Activity Implenents OnEditoractionListener, OnClickListener ( Step 2b: Implement the interface for the listener eoverride public void onClick(View v) ( switch (v. tipPercent = tippercent - .01f; calculateandDisplay(); break; case R.id.percentUpButton: tipPercent = tiprercent + .01f; calculateandDisplay(); break; > Step 3: Set the listeners percentupButton.setonClickiistener (this); percentDownButton.setonclickL: Description ‘The steps for handling the Click event are the same as the steps for handling the EditorAction event. However, since the Click event is wired to two buttons, the code in the onClick method includes a switch statement that checks which button was clicked and executes the appropriate code. To specify a literal value for the float type, you can append an f or an F to the number Figure 3-13 How to handle the Click event104 — Section 1 Get started fast with Android The lifecycle of an activity The Activity class defines methods that are called by the Android operating system at different points in the lifecycle of an activity. This is shown by figure 3-14. When you create an activity, you create a class that inherits the Activity class. Then, to get your app to work the way you want, you override the lifecycle methods to control the lifecycle of the activity. For example, you have already seen how you can override the onCreate method to display and prepare the user interface for an activity. However, you often need to override other methods to make sure that your app doesn’t lose its progress if the user leaves the app and returns to it later. Similarly, you often need to make sure that your app doesn’t lose its progress when the user switches between landscape and portrait orientation. When an app starts for the first time, Android calls the onCreate, onStart, and onResume methods. As this happens, the activity quickly passes through the created state and the started state. Of these three methods, the onCreate method is typically used to create the user interface and prepare it for display. In the Tip Calculator activity, for example, this method displays the user interface, gets references to important widgets, and wires the event handlers. After the onResume method executes, the app is in the running state, which is also known as the active state or resumed state. In this state, the app is visible and has the focus. Unlike the created and started states, an app may remain in the running state for a long time, If the running activity loses the focus, becomes partially covered by another activity, or if the device goes to sleep, Android calls the onPause method. This causes the activity to go into the paused state. Android altemp(s to maintain the state of all activities in the paused state. As a result, if the activity regains the focus or the device wakes up, Android can call the onResume method and return (o the running state without losing any of the user's progress. If the user gets a phone call or navigates to another activity, Android calls the onPause method followed by the onStop method. This causes the activity to g0 into the stopped state. In the stopped state, Android attempts to maintain the state of the activity for as long as possible. However, an activity in the stopped state has a lower priority than an activity in the running or paused states. AS a result, Android often kills activities that are in the stopped state. Most lifecycle methods have a corresponding method. If you implement one ‘method, it often makes sense to implement the other, For example, if you use the onPause method to save data when the activity goes into the paused state, you typically want to use the onResume method to restore the data when the activity retums to the running state, Similarly, if you use the onStop method, you typi- cally want to use the onStart method, and possibly the onRestart method. Although this diagram shows the most commonly used lifecycle methods for an activity, it doesn’t show them all, For example, in chapter 8, you'll learn more about working with the lifecycle methods for displaying menus. Or, you can carn more about other lifecycle methods by looking up the Activity class in the documentation for the Android API.Chapter 3 How to develop your first Android app 105 The lifecycle of an activity ‘onResumet) ‘onPause() ‘onResumet) constart!) ' ‘ontoy onstarti) ee L__onrestart) onCreate() ‘onDestroy!) Android eee Three common states Pern ‘This state is also known asthe active stare or the running state. A running activity is visible and has the focus. Android only destroys a resumed activity in extreme situations, such as if the activity tres to use sore memory than is available on the device A paused activity has lost the focus and may be partially hidden by other activites, or the device has gone to sleep. A paused activity typically maintains all states, Android only destroys a paused activity if necessary to keep the activity that’s in the running state stable and responsive. Stopped The activity has lost the focus and is completely hidden by another activ- ity. Android tries to retain the state for a stopped activity for as long as possible, However, stopped activities have a lower priority than the other two states. As a result, Android destroys activities in the stopped state whenever it’s necessary to allow activities with higher priorities to run, Description © When you create an activity, Android calls the methods of the Activity class at different points in its lifecycle. To get your app to work the way you want, you ean override these methods. * An activity passes through the created state and the started state quickly, but it can spend a long time in the resumed state, the paused state, and the stopped state. © Although this diagram shows the most commonly used lifecycle methods for an activity, it doesn’t show them all. To learn more about other lifecycle methods available to an activity, you can look up the Activity class in the documentation for the Android API. Figure 3-14 The lifecycle of an activity106 — Section 1 Get started fast with Android How to save and restore values Android doesn’t always save the data of an activity when the activity moves from the running state into the paused or stopped states. These states occur when the user navigates to another activity or when the user changes the orientation of the screen. For the Tip Calculator app, this means that the activity won’t always save the bill amount and the tip percent. As a result, if you only implement the onCreate method, the tip percent will be reset to its default value of 15% every time the user changes the orientation of the screen. Worse, the bill amount and the tip percent will be reset to their default values every time the user navigates to another activity and returns to the current activity. Since you usually want to save a user's progress, you typically want to save and restore these values as described in figure 3-15. To start, you need a way to permanently save values. Fortunately, the SharedPreferences class provided by the Android API makes this easy to do. First, you import the SharedPreferences class and its Editor class. Then, you declare a SharedPreferences object as an instance variable, and you use the onCreate method to create an instance of this object. In this figure, for example, the onCreate method uses the getSharedPreferences method to get a SharedPreferences object named saved Values. This object saves values to a file named SavedValues, and this file is only available to this activity, Once you have created a SharedPreferences object, you can override the onPause method and use the SharedPreferences object to save values. ‘To do that, you can call the edit method of the SharedPreferences object to get an Editor object. Then, you can use the methods of the Editor object to store the bill amount string and the lip percent, which are both instance variables. Next, this code calls the commit method from the Editor object to save the values in the editor object to disk. Finally, the last statement calls the onPause method of the superclass, which is necessary for the superclass to work correctly, To restore values that you have saved, you can override the onResume method, Within this method, the first statement calls the onResume method of the superclass, which is required for the superclass to work correctly. Then, the next two statements use the get methods of the SharedPreferences object to restore the instance variables for the bill amount string and tip percent. When you work with the Editor and SharedPreferences objects, you can use them to put and get values for strings and most primitive types. In this figure, for example, the instance variable for the bill amount variable is a string value, and the instance variable for the tip percent is a float value. However, the Editor and SharedPreferences objects don’t allow you to work directly with double values. So, if you want to use a double value, you must first cast it to a float value. To test the onPause and onRestore methods in an emulator, you can run the Tip Calculator activity and navigate to an activity in another app. Then, you can navigate back to the Tip Calculator activity. Or, if you want, you can change the orientation of the Tip Calculator activity in your emulator by pressing Ctrl+F11 or Numpad 7Chapter 3. Howto develop your first Android app 107 How to import the SharedPreferences class and its Editor class import android.content sharedPreferences; import android content sharedPreferences.Editor; How to set up the instance variables 1 @efine SharedPreferences object private SharedPreferences savedValues; soverrial public void onCreate(Bundle savedinstancestate) ¢ // other code goes here 1) get. SharedPreferences object savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE); > How to use the onPause method to save values eoverriae public void onPause() ( W save the instance variables Editor editor = savedValues.edit(); editor.putstring("billAmountstring", billAmountstring); editor.putFloat("tipPercent", tipPercent); editer.commit(); super.onPause(); How to use the onResume method to restore values eoverride public void onResume() ( super-onResune(); WI get the instance variabl billamountstring = savedValues.getstring("billamountstring", "™); tippercent = savedvalues.getFloat("tipPercent™, 0.15f); Description Android doesn’t always save the data of an activity when you change orientation or when you navigate away from an activity to another activity or app. * To save data for an activity, you can override the onPause method, * Torestore data for an activity, you can override the onResume method. You can use a SharedPreferences object and its Editor class to save and restore data To change orientation in an emulator, you can press Ctrl+F11 or Numpad 7. Figure 3-15 How to save and restore values108 — Section 1 Get started fast with Android How to use the documentation for the Android API One of the most difficult aspects of learning Android is mastering the hundreds of classes and methods that your apps will require. To do that, you frequently need to study the documentation for the Android API. If you've used the documentation for the Java API, you'll find that the Android API works similarly. Figure 3-16 summarizes some of the basic techniques for navigating through the documentation for the Android API. This shows one screen of the documen- tation available from the Activity class, which has many screens. To view the documentation for the Activity class, you click on the package name (android. app) in the upper left frame and then on the class name (Activity) in the lower left frame, If you scroll through the documentation for this class, you'll get an idea of the scale of the documentation that you're dealing with. After a few pages of overview information, you come to a summary of the constants, fields, and constructors available from the class. After that, you come to a summary of the dozens of public and protected methods that the class offers. That in turn is, followed by more detail about these constants, fields, constructors, and methods, At this point in your Android education, this is far more information than you can handle. That's why one of the goals of this book is to introduce you to the dozens of classes and methods that you'll use in most of the Android apps that you develop, Once you've learned those, the documentation for the Android API will make more sense to you, and you'll be able to use that documentation to research classes and methods that aren't presented in this book It's never too early to start using the documentation, though. So by all means use the documentation to get more information about the methods that are presented in this book and to research the other methods that are offered by the classes that are presented in this book. After you learn how to use the Activity class, for example, take some time to do some research on that class.Chapter 3 How to develop your first Android app 109 a ee ne RTS BT EN : nce utter eae r= ta) Cate hen a tty Younes gv yo te equestode youtaed wh he ‘eutcose teamed a ay anal tao ont emesscarce (esses hen thee ei oan at) (hed esTene ir and geen) app tame esue hc Then ect. cncseilechged cy eg charsequnc ovine svete ‘led vente act tng rcateog eh is eto was dread n Ame nrpne sn fo ee20369 3 onceiaog ie ag) ‘Themed wat pectin Pee set ew soca men a Wi Framestoree mad esa all nO Bons rouge re compat boone rote Prem anya clanp bet an at esto ewe etet te) “hi cad acts hat et cde glo nt pacha ta ce wed he Pot server stir Te Ragen cang ssertorsr cere ‘aed por oft civ eee wen an cvs gan to each bet a te Description © The Android API contains hundreds of classes and methods that you can use in your apps. © You can use a browser to view the documentation for the Android API by going to this address: http: //developer.android.con/reference/ * You can select the name of the package in the top left frame to display information about the package and the classes it contains. Then, you can select a class in the lower left frame to display the documentation for that class in the right frame. + Once you display the documentation for a class, you can scroll through it or click ona hyperlink to get more information. * To make it easier to access the documentation for the Android API, you should ‘bookmark the index page. Then, you can easily redisplay this page whenever you need it. Figure 3-16 How to use the documentation for the Android API110 Section 1 Get started fast with Android The Java code for the app Figure 3-17 shows the Java code for the Tip Calculator app. The code in this figure is similar to the Java code presented in chapter 1. By now, though, you should understand the details of how this code works. To start, the package statement stores the class for the Tip Calculator activity in the package named com.murach.tipcalculator. Then, it imports all Java and Android classes and interfaces that are needed for this class. If you review these classes and interfaces, you should be familiar with all of them. The TipCalculatorActivity class inherits the Activity class that’s provided by Android. In addition, this class implements the listener interfaces for the EditorAction and Click events. As a result, this class must implement the onEditorAction and onClick methods, Within the class, the first six statements define the instance variables for the widgets that the class needs to work with. Then, the seventh statement defines the SharedPreferences object that’s used to save and restore values, and the next two statements define instance variables for the bill amount string and the tip percent The onCreate method begins by calling the onCreate method of the super- class, which is necessary for the superclass to work correctly. Then, it uses the setContentView method that’s available from the superclass to display the user interface that’s defined in the XML file for the activity. After displaying the user interface, the onCreate method gets references to the six widgets that it declared earlier. To do that, it calls the findViewByld method for each widget. Then, it casts the View object that’s returned to the appropriate type for the widget. ‘Alter getting references to the widgets, this code sets the listeners. First, it sets the current class as the listener for the EditorAction event on the editable text view for the bill amount. Then, this code sets the current class as the listener for the Click event on both of the buttonsChapter 3 How 10 develop your first Android app The Java code Page 1 package com.murach.tipcalculator; import java.text NumberFormat; import android.os.Bundli import android view.KeyEvent; import android.view.view: import android view.view.onClickListene) import andreid.view.inputmethod.Editerinto; import android widget.Button; import android widget .zaitText; import android widget .TextView; import android widget. TextView.onzditorActionListener; import android app.Activity; import android.content.SharedPreferences; import android.content.sharedPreferences. Editor; public class TipcalculatorActivity extends Activity implements OnEditorActionListener, OnClickbistener ( 1 fine variables for the widgets private EditText billancuntEditrext; private TextView percentTextView; private Button percentupButton; private Button percentDewnButton; private TextView tipTextView private TextView totalTextViews 17 @ofine SharedPreferences object private SharedPreferences savedValues; 1 @efine an instance variable for the tip percent private String billamountstring = "™ private float tipPercent = 15£, Goverride public void oncreate(Bundle savedinstancestate) ( super.onCreate(savedinatancestate); setContentView(R-layout activity tip_calculater); UI get references to the widgets billAmountEditText = (BditText) findViewByzd(R.id.billAmountEditrext); percentTextView = (TextView) findViewById(R.id percentTextView); PercentUpButton = (Button) findViewById(R.id.percentUpButton) percentDownButton = (Button) findViewsyTa(R.id.percentDownButton); tiptextView = (TextView) findViewByrd(R.id.tiptextview); totalTextView = (TextView) findViewsyrd(R.id totalTextView); W/ set the listeners billAnountEditText setonEditoractionListener (thi: percentUpButton.setOnClickListener(this); percentDownButton.setonClickListener (this); Figure 3-17 The Java code (part 1 of 3) 11112 Section 1 Get started fast with Android The onPause method saves both of this activity’s instance variables: the bill amount string and the tip percent. These instance variables need to be saved for the app to work correctly when orientation changes and when the user navigates away from and back to this activity. The onResume method restores both of the activity’s instance variables. Then, it sets the bill amount string as the display text on the bill amount EditText widget. This is necessary because Android sets the display text to its default value if the user navigates away from and back to this activity. Finally, this code calls the calculateAndDisplay method. The calculateAndDisplay method calculates the tip and total amounts for the bill and displays all current data on the user interface. First, this method gets the bill amount from the EditText widget and converts this string to a float value. Then, it calculates the tip and total amounts and stores them as float values. Finally, it formats these float values and displays them on their corresponding widgets,Chapter 3 How to develop your first Android app 118 The Java code Page 2 1] get Sharedpreferences object savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE); > eoverride public void onPause() ( WJ save the instance variables Editor editor = savedValues.edit (); editor.putstring(*billAmountstring", billAmountstring); editor.putFloat ("tipPercent", tipPercent); editor.commit (); super.onPause(); > eoverride public void onkesume() ( ‘super.onResume(); WJ got the instance variable: billanountstring = savedValues.getString(*billamountstring", ""); tipPercent = savedValues.getPloat("tipPercent™, 0.15f) // act the bill amount on its widget billanounteditrext.setrext (billancuntstring); 1] calculate and display ealculateandDisplay(); > public void calculateandpisplay() ( 1] get the bill amount billAmountString = billAmountEditText.getText().tostring(); float billaAmount; if (billAmountstring.equals("™)) ( billamount = 0; « billAmount = Float.parseFloat (billAmountstring); > 17 calculate tip and total float tipAmount = billAmount * tipPercent; float totalAmount = billAmount + tipAmount; W/ display the other results with formatting NumberFormat currency = NumberFormat getCurrencyrnstance(); tiptextView.set Text (currency.format (tipAmount)); total Text View. set Text (currency.format (totalAmount)); NumberFormat percent = NumberFormat.getPercentinstance(); percentTextView. setToxt (percent format (tipPercent)); Figure 3-17 The Java code (part 2 of 3)114 Section 1 Get started fast with Android The onEditorAction method is executed whenever the user presses an action key on a soft keyboard such as the Done key. This method begins by using an if statement to check whether the action key is the Done key. If so, it calls the calculateAndDisplay method to perform the calculation and display the results on the user interface. The onClick method is executed whenever the user clicks on either of the buttons. Within this method, a switch statement checks which button was clicked. Then, if the Decrease (-) button is clicked, this code decreases the tip percent by 1 percent and calls the calculateAndDisplay method to perform the calculation and display the results on the user interface. Conversely, if the Increase (+) button is clicked, this code increases the tip percent by I percent and calls the calculateAndDisplay method to perform the calculation and display the results on the user interface.Chapter $+ How to develop your first Android app The Java code Page 3 override public boolean onBditorAction(TextView v, int actionTd, Keyzvent event) Af (actionza == Eaitorinfo.IMz_ACTION_DONE) « « calculateanapisplay(); > return false; > Goverride public void onclick(view v) ¢ iteh (vgetta()) € case R.id.percentDownButton: tipPercent = tipPercent - .01f; calculateandDisplay(); break: case R.id.percentupButton: tippercent = tipPercent + .01f; calculateanaDisplay(); Figure 3-17 The Java code (part 3 of 3) 115116 Section 1 Get started fast with Android Perspective The goal of this chapter has been to get you off to a fast start with Android development, Now, if you understand the Tip Calculator app, you should also be able to develop simple Android apps of your own. Keep in mind, though, that this chapter is just an introduction to the Android essentials that will be expanded upon in section 2 of this book. Terms widgets event controls action key text view listener label action event editable text view wire text box input method editor button created state layout started state form running state activity active state density-independent pixels resumed state scale-independent pixels paused state theme stopped state event handler Summary + In Android development, the components that make up the user interface are known as widgets. + In Android, a layout consists of one or more child elements and controls how those child elements are displayed. «In Eclipse, you can add widgets to a layout by dragging them from the Palette onto the layout in the Graphical Layout editor. + It’s generally considered a best practice to store the display text for your app in a separate XML file. This makes it easy to internationalize the text for your application. * Although Android supports other units of measurement, such as inches, it’s a best practice to use density-independent and scale-independent pixels whenever possible An event handler is a special type of method that’s executed when an event oceurs, * A listener is an object that listens for an event. * An EditorAction event typically occurs when the user presses an action key, such as the Done key, on a soft keyboard.Chapter 3. Howto develop your first Android app 47 A Click event typically occurs when the user clicks a widget such asa button, You can use the SharedPreferences class to permanently save values in your app. To save values, you can override the onPause method. To restore values you have saved, you can override the onResume method. Before you do the exercises for this chapter If you haven't already done so, you should install the software and the source code for this book as described in the appendix. Exercise 3-1 Create the Invoice Total app In this exercise, you'll create the Invoice Total app. When you're done, a test run should look something like this: Subtotal Discount Percent Discount Amount $15.00 Total $135.00 Create the project 1. Create a project for an Android app named Invoice Total and store it in a project named ch03_ex1_Invoice in this directory: \murach\android\workspace This project should be stored in a package named com.murach invoice. 2. Optionally, use the New Android Application dialog box to create a custom launcher icon. You should be able to download possible icons by searching the Internet. 3. Use the New Android Application dialog box to create a blank activity with a Java class for the activity named InvoiceTotalActivity and a layout file for the activity named activity_invoice_total. Create the user interface 4, [Wnecessary, open the XML file for the user interface that’s in the res\layout directory and switch to the Graphical Layout editor. 5. Use the Outline view to make sure the layout is a relative layout, If the Task List view is open, I recommend closing it118 Section | Get started fast with Android 6. Use the Outline view to delete the TextView widget that displays the “Hello world!” message. 7. Add the seven TextView widgets and one EditText widget to the layout. Set the Id and Text properties of each widget immediately after you add the widget. When you're done, the user interface should have the widgets and text shown above. However, these widgets may look different since you haven't set their properties yet. 8. Set the Text Size property for all eight widgets to 20sp. Set the Text Style property for the four widgets in the left column to bold 10, Switch to the XML editor and review the code, Note how the XML attributes match the properties that you have set with the Graphical Layout editor. 11, Open the strings.xm file that’s in the res/values directory. If necessary, switch to the XML editor view. Then, review the code. 12. Delete the string named hello_world. 13, Test the user interface by running the app on a physical device or an emulator. The app should allow you to enter a subtotal, but that won't change the discount percent, discount amount, or total. Write the Java code 14. Open the InvoiceTotal Activity java file that’s in the ste directory of the project 15, Delete all methods except the onCreate method. 16. Use the onCreate method to get references to the EditText widget and the three TextView widgets that display data. 17. Create a method named calculateAndDisplay. This method should get the subtotal value, Then, it should calculate the discount amount and total. It should give a 20% discount if the subtotal is greater than or equal to 200, a 10% discount if the subtotal is greater than or equal to 100, and no discount if the subtotal is less than 100. 18. Add code to the end of the calculateAndDisplay method that displays the results of the calculation on the widgets for the discount percent, discount amount, and total. 19, Override the onResume method and use it to call the calculateAndDisplay method, 20. Handle the EditorAction event for the EditText widget so that it executes the calculateAndDisplay method when the Done key is pressed 21, Test the app. It should display the starting values that are coded in the strings. xml file, 22. Modify the strings.xml file so it doesn’t display a starting value for the subtotal. 23, Test the app again. This time, it shouldn't display a starting value for the subtotal, Enter some values for the subtotal and make sure it works correctly.24. 26. 21. Chapter 3 How to develop your first Android app 119 Change the orientation of the activity. On an emulator, you can do that by pressing Ctrl+F11 or Numpad 7. The activity should retain all of its data. Press the Back key to navigate away from the app. Then, navigate back to the app. In an emulator, you can do this by clicking on the Settings icon, selecting the Apps tab, and clicking on the Invoice Total app. The activity should lose all of its data. Override the onPause method so it saves the string for the subtotal. Then, modify the onResume method so it gets the string for the subtotal. To get these methods to work correctly, you need to set up instance variables for the subtotal string and for a SharedPreferences object that you can use to save and get this string. Test the app again. This time, the app should always remember the last subtotal that you entered even if you navigate away from the app and return to it, In addition, the app should always calculate and display the correct values for the discount percent, discount amount, and total. Exercise 3-2 Use the documentation for the Android API This exercise steps you through the documentation for the Android API. This should give you an idea of how extensive the Android APT is. Open a browser and display the documentation for the Android APL Click the android app package in the upper left frame and the Activity class in the lower left frame to display the documentation for the Activity class. Then, scroll through this documentation to get an idea of its scope ‘Skim through the overview information for the Activity class. Scroll through the public methods. These methods include the find ViewByld and setContentView methods that you learned how to use in this chapter. Scroll through the protected methods, These methods include the onCreate, onPause, and onResume methods that you learned how to override in this chapter. Go to the documentation for the TextView class, which is in the android.widget package. Review the attributes for this class as well as the public methods for this class. The public methods include the getText and setText methods you learned about in this chapter. Go to the documentation for the SharedPreferences interface, which is in the android.content package. Then, review public methods. These methods provide a way to get strings as well as values of the boolean, int, long, and float types. However, they don't provide a way to get values of the double type.How to test and debug an Android app As you develop an Android app, you need to test it to make sure that it performs as expected. Then, if there are any problems, you need to debug your app to correct any problems. This chapter shows how to do both. Basic skills for testing and debugging ‘Typical test phases. How to check the layout. ‘The three types of erxors How to handle runtime errors, How to trace code execution. How to use LogCat logging How to use toasts How to use the debugger . How to set and remove breakpoints How to step through code. How to inspect variables. How to inspect the stack trace How to configure step filters, How to configure your emulators... How to add an emulator for an old phone How to work with an emulator for an old phone. How to add an emulator for a tablet Perspective122 Section 1 Get started fast with Android Basic skills for testing and debugging When you est an app, you run it to make sure that it works correctly. As you test the app, you try every possible combination of input data and user actions to be certain that the app works in every case. In other words, the goal of testing is to find errors (bugs) and make an app fail. When you debug an app, you fix the bugs that you discover during testing, Each time you fix a bug, you test again to make sure that the change you made didn’t affect any other aspect of the app. Typical test phases When you test an app, you typically do so in phases, like the four that are summarized in figure 4-1 In the first phase, you should test the user interface. To start, you can use the Graphical Layout editor to check the widgets to make sure they display properly. ‘As you do this, you should test portrait and landscape orientation, all target screen sizes, and all target platforms. You'll learn how to do that in the next figure, Then, you should run the app on a device or emulator to make sure that all the widgets work correctly. For instance, you can click on an EditText widget to make sure the soft keyboard displays correctly. In the second phase, you should test the app with valid data, To start, you can run the app and enter data that you would expect a user to enter. Then, you should enter valid data that tests the limits of the app. You should change the orientation of the app to make sure it works correctly when the user switches between portrait and landscape orientation. And you should test other changes in the lifecycle of each activity. For instance, you should navigate away from an activity and return to it. In the third phase, you should try to make the app fail by testing every combination of invalid data and user action that you can think of. For instance, if possible, you should try entering letters where numbers are expected In the first three phases, you can test the app on a single device or emulator. If possible, this device should be the primary target device. For example, if you primarily want your app to run on a current touchscreen smartphone, you can begin by testing on that device or an emulator that emulates that device. In the fourth phase, the app should be working correctly on the primary target device or emulator. However, in this phase, you test the app on all other (arget devices or on emulators for those devices. This may include devices that have physical keyboards, D-pads, or other custom hardware. If possible, you should use physical devices since this is the only true way (o test your app. However, whenever necessary, you can use an emulator instead of a physical device. As you test on various target devices, you will usually find some bugs that you'll need to fix. This is one of the most difficult aspects of Android programming,Chapter44 How totest and debug an Android app 128, The Tip Calculator with a logic error @ Tip calculator Bill Amount 34.60 Percent Tip Total Four test phases * Check the user interface to make sure that it works correctly. = Check in portrait and landscape orientation, - Check on all target screen sizes - Check on all target platforms. ‘Test the app with valid input data to make sure the results are correct. - Test changing the orientation. - Test other changes in the lifecycle of the activity. ‘Test the app with invalid data or unexpected user actions. Try everything you can think of to make the application fail + Test on all target devices. This may include devices that have a physical keyboard, D-pad, or other kinds of hardware. Use a physical device if possible. Otherwise, use an emulator. Description The goal of resting is to find all errors (bugs) in the app. The goal of debugging is to fix all of the bugs that you find during testing, Figure 4-1 An introduction to testing and debugging124 Section | Get started fast with Android How to check the layout Figure 4-2 shows how to use the Graphical Layout editor to check the layout. To start, you can use the buttons on the toolbar to zoom in of out. Or, you can emulate the real size of the device by clicking on the Emulate Real Size button, These skills can help you view the widgets on the user interface and make sure that they are being displayed correctly. If you are going to allow the app to switch orientations, you need to make sure the layout works for both portrait and landscape orientation. To do that, you can click on the Flip Orientation button in the toolbar to switch between portrait and landscape orientation, Then, you can check to make sure the layout displays correctly in both orientations. If it doesn’t, you can tweak it until it does, or you can create a separate layout for each orientation as described in the next chapter. Once the layout displays correctly in both orientations, you should test it for different screen sizes. To do that, you can use the drop-down list in the toolbar to select a device with a different screen size. In this figure, the Nexus One smart- phone is selected. This device has a 3.7 inch screen. However, if you want you can select a tablet with a 7 or 10 inch screen. Once you are satisfied with the layout in different screen sizes, you should test it on different platforms. To do that, you can select any platform that’s installed on your system from the drop-down list in the toolbar. In this figure, for example, four platforms are installed on the user's system. When you do this, it may take your system a minute or so to render the user interface, so be patient! When the device is displayed on the new platform, the widgets may look differ- ent, but the layout should still display correctly. Finally, if you need to change the theme, you can do that by selecting a different theme from the drop-down list in the toolbar. In this figure, the theme named AppTheme has been selected, which is usually what you want. However, if necessary, you can use the drop-down list to select another theme.
You might also like
Joel Murach, Mary Delamater - Murach's C++ Programming-Mike Murach & Associates (2018) PDF
PDF
100% (7)
Joel Murach, Mary Delamater - Murach's C++ Programming-Mike Murach & Associates (2018) PDF
802 pages
MurachC# Sharp Sanet - ST
PDF
83% (6)
MurachC# Sharp Sanet - ST
816 pages
Murach's HTML5 and CSS3-Verson 4
PDF
67% (3)
Murach's HTML5 and CSS3-Verson 4
738 pages
Joel Murach, Michael Urban - Murach's Java Servlets and JSP (3rd Edition) (Training & Reference) - 2014 PDF
PDF
100% (2)
Joel Murach, Michael Urban - Murach's Java Servlets and JSP (3rd Edition) (Training & Reference) - 2014 PDF
767 pages
Murach's Java Programming
PDF
100% (9)
Murach's Java Programming
830 pages
Kotlin Apprentice 3rd Edition 2021 Irina Galata Joe Howard Ellen Shapiro
PDF
100% (8)
Kotlin Apprentice 3rd Edition 2021 Irina Galata Joe Howard Ellen Shapiro
491 pages
Android App Development
PDF
No ratings yet
Android App Development
983 pages
Murach's ASP - Net 4.6 Web Programming With C# 2015 (2016)
PDF
88% (8)
Murach's ASP - Net 4.6 Web Programming With C# 2015 (2016)
952 pages
Joel Murach, Michael Urban-Murach's Beginning Java With Eclipse-Mike Murach & Associates (2015)
PDF
100% (3)
Joel Murach, Michael Urban-Murach's Beginning Java With Eclipse-Mike Murach & Associates (2015)
662 pages
Murachs HTML5 and CSS3 3rd Edition by Anne Boehm, Zak Ruvalcaba
PDF
67% (9)
Murachs HTML5 and CSS3 3rd Edition by Anne Boehm, Zak Ruvalcaba
703 pages
Android Programming Concepts
PDF
67% (3)
Android Programming Concepts
44 pages
Murach's Visual Basic 2010
PDF
100% (4)
Murach's Visual Basic 2010
856 pages
Teach Yourself Game Programming With DirectX in 21 Days
PDF
100% (3)
Teach Yourself Game Programming With DirectX in 21 Days
720 pages
Programming Games Java Swing Tutorial
PDF
100% (4)
Programming Games Java Swing Tutorial
998 pages
Beginning Java Game Programming Second Edition
PDF
80% (5)
Beginning Java Game Programming Second Edition
359 pages
Mike Murach Murachs Csharp 2012 5th Edition 1890774723
PDF
100% (3)
Mike Murach Murachs Csharp 2012 5th Edition 1890774723
872 pages
Modern Web Development With Kotlin Sample PDF
PDF
0% (3)
Modern Web Development With Kotlin Sample PDF
33 pages
(Create Your Own App) - Kotlin Development For Android-Independently
PDF
No ratings yet
(Create Your Own App) - Kotlin Development For Android-Independently
53 pages
Advanced Java
PDF
89% (9)
Advanced Java
333 pages
Book
PDF
0% (1)
Book
7 pages
Android App Development in Android Studio Java+Android Edition For Beginners
PDF
100% (1)
Android App Development in Android Studio Java+Android Edition For Beginners
214 pages
Beginning Android Development
PDF
75% (4)
Beginning Android Development
721 pages
Android
PDF
100% (6)
Android
1,595 pages
Android Test-Driven Development by Tutorials
PDF
100% (2)
Android Test-Driven Development by Tutorials
484 pages
Language C. - 3D Apple Games by Tutorials (3rd Edition) - 2017 PDF
PDF
100% (2)
Language C. - 3D Apple Games by Tutorials (3rd Edition) - 2017 PDF
473 pages
PDF - 760 - 760412 810186 810998 9780596526849 Subqueries PDF
PDF
100% (1)
PDF - 760 - 760412 810186 810998 9780596526849 Subqueries PDF
40 pages
Android Programming
PDF
94% (16)
Android Programming
817 pages
Android Programming
PDF
100% (2)
Android Programming
27 pages
Alberto Montalesi Complete Guide To Modern JavaScript - 2020
PDF
100% (1)
Alberto Montalesi Complete Guide To Modern JavaScript - 2020
204 pages
Edumobile: Beginning Your Android Programming Journey
PDF
100% (1)
Edumobile: Beginning Your Android Programming Journey
28 pages
Composing Mobile App, Learn - E - Anil V Deshpande Anubhav Pradha
PDF
63% (8)
Composing Mobile App, Learn - E - Anil V Deshpande Anubhav Pradha
288 pages
Android Programming For Beginners
PDF
67% (3)
Android Programming For Beginners
94 pages
Angular 8
PDF
100% (1)
Angular 8
98 pages
Android Game Development
PDF
No ratings yet
Android Game Development
201 pages
Special Edition Using Java 2 Platform - Que
PDF
100% (1)
Special Edition Using Java 2 Platform - Que
1,191 pages
0903 Learning Ios
PDF
No ratings yet
0903 Learning Ios
1,117 pages
Java Interview Questions
PDF
No ratings yet
Java Interview Questions
11 pages
Programming Abstractions in C++
PDF
100% (2)
Programming Abstractions in C++
682 pages
Android App Development & Programming Guide Learn in A Day!
PDF
100% (6)
Android App Development & Programming Guide Learn in A Day!
145 pages
JAVA Swing 2nd Edition - Manning
PDF
0% (1)
JAVA Swing 2nd Edition - Manning
903 pages
Mastering PHP
PDF
50% (2)
Mastering PHP
18 pages
Introduction To Classes: Fields Declaration
PDF
100% (1)
Introduction To Classes: Fields Declaration
19 pages
C++ For Game Programming
PDF
100% (8)
C++ For Game Programming
434 pages
Murach's Android Programming Training & Reference 2nd Edition
PDF
No ratings yet
Murach's Android Programming Training & Reference 2nd Edition
683 pages
Beginning Android Programming: Develop and Design
PDF
No ratings yet
Beginning Android Programming: Develop and Design
7 pages
Android Tutorial
PDF
No ratings yet
Android Tutorial
218 pages
Android Application Development Cookbook Boyer 2024 Scribd Download
PDF
100% (5)
Android Application Development Cookbook Boyer 2024 Scribd Download
62 pages
Android UI Fundamentals - Develop & Design
PDF
67% (3)
Android UI Fundamentals - Develop & Design
337 pages
Android Application Development Cookbook Boyer 2024 scribd download
PDF
100% (3)
Android Application Development Cookbook Boyer 2024 scribd download
55 pages
Code Gems For Androd
PDF
No ratings yet
Code Gems For Androd
7 pages
Creating Our First Android App: Licensed Under Creative Commons Attribution 2.5 License. All Rights Reserved
PDF
No ratings yet
Creating Our First Android App: Licensed Under Creative Commons Attribution 2.5 License. All Rights Reserved
25 pages
45266
PDF
No ratings yet
45266
51 pages
(Ebook) Android Application Development Cookbook Second Edition (2016) by Rick Boyer, Kyle Mew ISBN 9181809815123 instant download
PDF
100% (2)
(Ebook) Android Application Development Cookbook Second Edition (2016) by Rick Boyer, Kyle Mew ISBN 9181809815123 instant download
47 pages
Android Application Development Cookbook Boyer all chapter instant download
PDF
100% (8)
Android Application Development Cookbook Boyer all chapter instant download
55 pages
(Ebook) Android Application Development Cookbook Second Edition (2016) by Rick Boyer, Kyle Mew ISBN 9181809815123 - Get the ebook in PDF format for a complete experience
PDF
100% (1)
(Ebook) Android Application Development Cookbook Second Edition (2016) by Rick Boyer, Kyle Mew ISBN 9181809815123 - Get the ebook in PDF format for a complete experience
60 pages
Android Programming For Beginners - Sample Chapter
PDF
No ratings yet
Android Programming For Beginners - Sample Chapter
50 pages
Android Application Development Cookbook Second Edition Rick Boyer download
PDF
No ratings yet
Android Application Development Cookbook Second Edition Rick Boyer download
52 pages
Introduction To Android
PDF
No ratings yet
Introduction To Android
43 pages
Week 1 Android Programming What Is Android?
PDF
No ratings yet
Week 1 Android Programming What Is Android?
47 pages
Review Udacity Android App Development
PDF
No ratings yet
Review Udacity Android App Development
12 pages