android-programming-for-beginners - Engenharia de Software I (2024)

android-programming-for-beginners - Engenharia de Software I (2)

android-programming-for-beginners - Engenharia de Software I (3)

android-programming-for-beginners - Engenharia de Software I (4)

android-programming-for-beginners - Engenharia de Software I (5)

android-programming-for-beginners - Engenharia de Software I (6)

android-programming-for-beginners - Engenharia de Software I (7)

android-programming-for-beginners - Engenharia de Software I (8)

android-programming-for-beginners - Engenharia de Software I (9)

android-programming-for-beginners - Engenharia de Software I (10)

android-programming-for-beginners - Engenharia de Software I (11)

Prévia do material em texto

Android Programming for Beginners Third EditionBuild in-depth, full-featured Android apps starting from zero programming experienceJohn HortonBIRMINGHAM—MUMBAITelegram Channel @IRFaraExamAndroid Programming for Beginners – Third EditionCopyright © 2021 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.Associate Group Product Manager: Pavan RamchandaniPublishing Product Manager: Rohit RajkumarSenior Editor: Keagan CarneiroContent Development Editor: Divya VijayanTechnical Editor: Shubham SharmaCopy Editor: Safis EditingProject Coordinator: Manthan PatelProofreader: Safis EditingIndexer: Rekha NairProduction Designer: Jyoti ChauhanFirst published: December 2015Second edition: October 2018Third edition: April 2021Production reference: 1080421Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirminghamB3 2PB, UK.ISBN 978-1-80056-343-8www.packt.comTelegram Channel @IRFaraExamhttp://www.packt.comContributorsAbout the authorJohn Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.Telegram Channel @IRFaraExamAbout the reviewersBrandon Kitt is a 24-year-old mobile app developer and enthusiast. He has worked on all kinds of projects, ranging from Java, Kotlin, Flutter, and a list of other non-mobile-specific applications, and is passionate about modern development and set on simplifying and accelerating all development processes.Brandon believes architecture, simplicity, and innovation are the building blocks of all great apps and the core foundation they are laid on. Through self-learning and an eye for clean, readable, and maintainable code, Brandon has furthered his education, exploring new technologies and toolkits that are released exceptionally quickly in the mobile development industry, to take full advantage of those changes in the process of making modern, attractive apps.Brandon's always available for partnership and collaboration whenever and wherever possible. You can reach Brandon on LinkedIn, Facebook, or on hotmail at brandon.kitt.Mohammed Fathy is a creative software engineer. He does what is possible with code in order to make life more efficient for people. He has been in the software engineering business for over 10 years, building new and innovative solutions for top companies in many countries. He works with Java and Kotlin to build Android apps.Telegram Channel @IRFaraExamTable of ContentsPreface1Beginning Android and JavaTechnical requirements 2What's new in the third edition? 3Why Java and Android? 3The beginner's first stumbling block 4How Java and Android work together 5Understanding the Android API 6Java is object-oriented 7Run that by me again – what exactly is Android? 9Android Studio 9Setting up Android Studio 10What makes an Android app? 13Android resources 13The structure of Android's Java code 14Packages 14Classes 15Methods 15Building our first Android app 16Deploying the app so far 21Running and debugging the app on an Android emulator 22Running the app on a real device 25Frequently asked questions 27Summary 272First Contact: Java, XML, and the UI DesignerTechnical requirements 30Examining the logcat output 30Filtering the logcat output 31Exploring the project Java and the main layout XML 31Examining the MainActivity.java file 32Examining the app layout file 35Adding buttons to the main layout file 39Adding a button via the visual designer 40Adding a button by editing the XML code 45Telegram Channel @IRFaraExamii Table of ContentsGiving the buttons unique id attributes 47Positioning the two buttons in the layout 48Making the buttons call different methods 51Leaving comments in our Java code 51Coding messages to the user and the developer 52Writing our first Java code 53Adding message code to the onCreate method 54Writing our own Java methods 56Frequently asked questions 59Summary 603Exploring Android Studio and the Project StructureTechnical requirements 62Project Explorer and project anatomy 62Exploring the file and folder structure of the Empty Activity project template 63Exploring an Empty Activity project 64Exploring the file and folder structure of the Basic Activity project template 79Exploring a Basic Activity project 80Exploring the Android emulator 89Emulator control panel 89Using the emulator as a real device 90Summary 934Getting Started with Layouts and Material DesignTechnical requirements 96Finding out about Material Design 96Exploring Android UI design 97Introducing layouts 98Creating and exploring a layout project 98Building a layout with LinearLayout 99Adding a LinearLayout layout type to a project 100Preparing your workspace 101Examining the generated XML 102Adding a TextView to the UI 103Wiring up the UI with the Java code (Part 1) 108Adding layouts within layouts 110Making the layout look pretty 115Wiring up the UI with Java code (Part 2) 117Building a precise UI with ConstraintLayout 117Adding a CalendarView 117Adding and constraining more UI elements 123Making the text clickable 127Telegram Channel @IRFaraExamTable of Contents iiiLaying out data with TableLayout 128Adding a TableRow element to TableLayout 129Organizing the table columns 132Linking back to the main menu 134Summary 1355Beautiful Layouts with CardView and ScrollViewTechnical requirements 138Attributes quick summary 138Sizing using dp 138Sizing fonts using sp 139Determining size with wrap or match 140Using padding and margin 142Using the layout_weight property 143Using gravity 145Building a UI with CardView and ScrollView 146Setting the view with Java code 147Adding image resources 147Creating the contents for the cards 149Defining dimensions for CardView 152Adding CardView to our layout 153Creating a tablet emulator 158Frequently asked question 161Summary 1616The Android LifecycleTechnical requirements 164The life and times of an Android app 164How Android interacts with our apps 164A simplified explanation of the Android lifecycle 165The lifecycle phases demystified 166How we handle the lifecycle phases 167Lifecycle demo app 170Coding the lifecycle demo app 170Running the lifecycle demo app 173Examining the lifecycle demo app output 174Some other overridden methods 176The structure of Java code – revisited 178Introducing fragments and the lifecycle 179Summary 180Telegram Channel @IRFaraExamiv Table of Contents7Java Variables, Operators, and ExpressionsTechnical requirements 182Java is everywhere 182Understanding Java syntax and jargon 183More code comments 184Storing and using data with variables 185Types of variables 187Using variables 192Variable declaration 192Variable initialization 193Changing values in variables with operators 194The assignment operator 194The addition operator 194The subtraction operator 195The division operator 195The multiplication operator195The increment operator 196The decrement operator 196Trying out expressions 197Expressing Yourself demo app 197Summary 2008Java Decisions and LoopsTechnical requirements 202Making decisions in Java 202Indenting code for clarity 202More operators 203How to use all these operators to test variables 206Switching to make decisions 210The switch demo app 211Repeating code with loops 213while loops 215do while loops 218for loops 220Loops demo app 221Summary 2259Learning Java MethodsTechnical requirements 228Methods revisited 228What exactly are Java methods? 228Method structure 229Modifier 230Return type 231Name of the method 233Telegram Channel @IRFaraExamTable of Contents vParameters 234The body 235Using method demo apps 236Real-world methods 236Exploring method overloading 239Scope and variables revisited 242Method recursion 243Questions 246Summary 247Further reading 24810Object-Oriented ProgrammingTechnical requirements 249Important memory management warning 250Object-oriented programming 250What is OOP exactly? 250Why do it like this? 252Class recap 253Looking at the code for a class 253Class implementation 253Declaring, initializing, and using an object of the class 254Basic classes app 258More things we can do with our first class 261Frequently asked questions 263Summary 26311More Object-Oriented ProgrammingTechnical requirements 266Remember that encapsulation thing? 266Controlling class use with access modifiers 267Controlling variable use with access modifiers 268Methods can have access modifiers too 269Accessing private variables with getters and setters 271Setting up our objects with constructors274Static methods 277Encapsulation and static methods mini-app 279OOP and inheritance 285Inheritance example app 287Polymorphism 292Abstract classes 293Interfaces 294Frequently asked questions 297Summary 297Telegram Channel @IRFaraExamvi Table of Contents12The Stack, the Heap, and the Garbage CollectorTechnical requirements 300All the Android UI elements are classes too 300Re-introducing references 300So how does this heap thing help me? 302Using buttons and TextView widgets from our layout 303Running the app 313Inner and anonymous classes 315Frequently asked questions 315Summary 31613Anonymous Classes – Bringing Android Widgets to LifeTechnical requirements 318Declaring and initializing the objects 318Creating UI widgets from pure Java without XML 319Exploring the palette – part 1 320The EditText widget 321The ImageView widget 321Radio buttons and groups 322Anonymous classes 324Exploring the palette and more anonymous classes – part 2 328Switch 328CheckBox 329TextClock 330Using WebView 331The Widget Exploration app 331Setting up the Widget Exploration project and UI 332Coding the Widget Exploration app 339Using WebView 348Running the Widget Exploration app 349Summary 35214Android Dialog WindowsTechnical requirements 354Dialog windows 354Creating the Dialog Demo project 354Coding a DialogFragment class 354Using the DialogFragment class 358The Note to Self app 361Using naming conventions and string resources 361How to get the code files for the Note to Self app 362The completed app 363Building the project 366Preparing the string resources 366Telegram Channel @IRFaraExamTable of Contents viiCoding the Note class 368Implementing the dialog designs 370Coding the dialog boxes 375Showing our new dialogs 383Summary 38915Arrays, Maps, and Random NumbersTechnical requirements 392A random diversion 392Handling large amounts of datawith arrays 393Arrays are objects 395Simple array example mini-app 396Getting dynamic with arrays 398Dynamic array example 398Entering the nth dimension with arrays 400Multidimensional array mini-app 400Array-out-of-bounds exceptions 404ArrayList 405The enhanced for loop 407Arrays and ArrayList instances are polymorphic 407More Java collections – meet the Java HashMap 409The Note to Self app 411Frequently asked questions 411Summary 41116Adapters and Recyclers Technical requirements 414RecyclerView and RecyclerAdapter 414The problem with displaying lots of widgets 414The solution to the problem of displaying lots of widgets 415How to use RecyclerView and RecyclerAdapter 415What we will do to set up RecyclerView with RecyclerAdapter and an ArrayList of notes 417Adding RecyclerView, RecyclerAdapter, and ArrayList to the Note to Self project 418Removing the temporary "Show Note" button and adding RecyclerView 418Creating a list item for RecyclerView 419Coding the RecyclerAdapter class 421Coding MainActivity to use the RecyclerView and RecyclerAdapter classes 429Running the app 433Frequently asked questions 435Summary 435Telegram Channel @IRFaraExamviii Table of Contents17Data Persistence and Sharing Technical requirements 438Android intents 438Switching Activity 438Passing data between activities 439Adding a settings page to Note to Self 440Creating SettingsActivity 441Designing the settings screen layout 442Enabling the user to switch to the settings screen 442Persisting data with SharedPreferences 444Reloading data with SharedPreferences 446Making the Note to Self settings persist 446Coding the SettingsActivity class 446Coding the MainActivity class 449More advanced persistence 451What is JSON? 452Java exceptions – try, catch, and finally 453Backing up user data in Note to Self 454Frequently asked questions 462Summary 46218LocalizationTechnical requirements 463Making the Note to Self app accessible for Spanish and German speakers 464Adding Spanish language support 464Adding German language support 464Adding the string resources 465Running Note to Self in German or Spanish 468Making the translations work in Java code 469Summary 47119Animations and InterpolationsTechnical requirements 473Animations in Android 474Designing cool animations in XML 474Instantiating animations and controlling them with Java code 477More animation features 477Animation demo app – introducing SeekBar 479Laying out the animation demo 479Telegram Channel @IRFaraExamTable of Contents ixCoding the XML animations 483Wiring up the animation demo app with Java 488Frequently asked questions 499Summary 50020Drawing GraphicsTechnical requirements 502Understanding the Canvas class 502Getting started drawing with Bitmap, Canvas, and ImageView 502Using the Canvas class 504Preparing the instances of the required classes 505Initializing the objects 505Setting the Activity content 506Canvas demo app 506Creating a new project 506The Android coordinate system 512Plotting and drawing 512Creating bitmaps 513Manipulating bitmaps 514What is a bitmap exactly? 514The Matrix class 515Bitmap manipulation demo app 518Adding the graphic to the project 518Frequently asked question 523Summary 52321Threads and Starting the Live Drawing App Technical requirements 526Creating the Live Drawing project 526Refactoring MainActivity to LiveDrawingActivity 526Locking the game to fullscreen and landscape orientation 527Looking ahead at the Live Drawing app 528Coding the LiveDrawingActivity class 529Coding the LiveDrawingView class 532Coding the LiveDrawingView class 534The game loop 543Threads 546Problems with threads 547Implementing the game loop with a thread 550Implementing Runnable and providing the run method 550Coding the thread 551Starting and stopping the thread 552Using the Activity lifecycle to start and stop the thread 553Coding the run method 554Running the app 558Summary 559Telegram Channel @IRFaraExamx Table of Contents22Particle Systems and Handling Screen Touches Technical requirements 562Adding custom buttons to the screen 562Implementing a particle system effect 563Coding the Particle class 564Coding the ParticleSystem class 566Spawning particle systems in the LiveDrawingView class 572Handling touches 574Coding the onTouchEvent method 576Finishing the HUD 578Running the app 579The Android Studio Profiler tool 581Summary 58323Supporting Different Versions of Android, Sound Effects, and Spinner WidgetHandling different versions of Android 586Detecting the current Android version 586The SoundPool class 587Initializing SoundPool the new way 587Initializing SoundPool the old way 589Sound demo app introducing the Spinner widget 592Making sound effects 592Laying out the sound demo 595Coding the sound demo 598Summary 60424Design Patterns, Multiple Layouts, and FragmentsTechnical requirements 606Introducing the model-view-controller pattern 606Android design guidelines 607Real-world apps 608Device detection mini-app 611Coding the MainActivity class 615Running the app 617Configuration qualifiers 619The limitation of configuration qualifiers 621Fragments 622Fragments have a lifecycle too 622Managing Fragments with FragmentManager 623Telegram Channel @IRFaraExamTable of Contents xiOur first Fragment app 624Fragment reality check 631Frequently asked question 632Summary 63225Building a Simple Image Gallery AppTechnical requirements 633Angry Birds classic swipe menu 634Building an image gallery/slider app 634Implementing the layout 635Coding the PagerAdapter class 636Coding the MainActivity class 640Running the gallery app 642Summary 64326Advanced UI with Navigation Drawer and FragmentTechnical requirements 646Introducing NavigationView 646Examining the Simple Databaseapp 647Insert 649Delete 649Search 650Results 650Starting the Simple Database project 651Exploring the autogenerated code and assets 652Coding the Fragment classes and their layouts 653Creating the empty files for the classes and layouts 654Coding the classes 654Designing the layouts 657Designing content_insert.xml 657Designing content_delete.xml 658Designing content_search.xml 659Designing content_results.xml 660Using the Fragment classes and their layouts 660Editing the Navigation Drawer menu 660Adding a holder to the main layout 661Coding the MainActivity.java class 662Summary 66727Android DatabasesTechnical requirements 670Databases 101 670What is a database? 670What is SQL? 671What is SQLite? 671SQL syntax primer 671Telegram Channel @IRFaraExamxii Table of ContentsSQLite example code 671Android SQLite API 674SQLiteOpenHelper and SQLiteDatabase 674Building and executing queries 674Database cursors 677Coding the database class 678Coding the Fragment classes to use the DataManager class 684Running the Age Database app 688Summary 69028A Quick Chat before You GoPublishing 692Make an app! 692Keep learning 693Keep reading 693GitHub 694Stack Overflow 694Android user forums 696Higher-level study 696My other channels 696Goodbye and thank you 697Why subscribe? 699Other Books You May EnjoyIndexTelegram Channel @IRFaraExamPrefaceAre you trying to start a career in programming, but haven't found the right way in? Do you have a great idea for an app, but don't know how to make it a reality? If so, then this book is for you!This updated third edition of Android Programming for Beginners will be your companion for creating Android applications from scratch. We will introduce you to all the fundamental concepts of programming in an Android context, from the basics of Java to working with the Android API. All examples use the up-to-date API classes and are created from within Android Studio, the official Android development environment that helps supercharge your application development process.Following this crash course, we'll dive deeper into Android programming and you'll learn how to create applications with a professional-standard UI through fragments and store your user's data with SQLite. In addition, you'll see how to make your apps multilingual, draw to the screen with a finger, and work with graphics, sound, and animations, too.By the end of this book, you'll be ready to start building your own custom applications in Android and Java.Who this book is forThis book is for you if you are completely new to Java, Android, or programming, and want to make Android applications. This book will also act as a refresher for those of you who already have experience of using Java on Android to enable you to advance your knowledge and make rapid progress through the early projects.Telegram Channel @IRFaraExamxiv PrefaceWhat this book coversChapter 1, Beginning Android and Java, will see you not waste any time in getting started with developing Android apps. We will look at what is so great about Android, what exactly Android and Java are, how they work and complement each other, and what that means to us as future developers. Moving quickly on, we will set up the required software so that we can build and deploy a simple first app.Chapter 2, First Contact: Java, XML, and the UI Designer, explains how, at this stage, we have a working Android development environment and we have built and deployed our first app. We need to explore this autogenerated code so that we can begin to understand Android and then learn how to build on this useful templateChapter 3, Exploring Android Studio and the Project Structure, explains how to create and run two more Android projects. The purpose of these exercises is to explore in more depth Android Studio and the structure of Android projects. Along with understanding the composition of our projects, it will also be beneficial to make sure we get the most from the emulator.Chapter 4, Getting Started with Layouts and Material Design, covers the building of three more layouts—still quite simple, yet a step up from what we have done so far. Before we get hands-on, we will have a quick introduction to the concept of Material Design. We will also cover the different types of layout called LinearLayout, ConstraintLayout, and TableLayout. We will also write some Java code to switch between our different layouts within a single app/project. This is the first major app that links together multiple topics in one neat parcel.Chapter 5, Beautiful Layouts with CardView and ScrollView, is the final chapter on layouts before we spend some time focusing on Java and object-oriented programming. We will formalize our learning on some of the different attributes we have already encountered, and we will also introduce two more cool layouts: ScrollView and CardView. To conclude this chapter, we will run a CardView project on a tablet emulator.Chapter 6, The Android Lifecycle, will see us become familiar with the lifecycle of an Android app. The lifecycle is the way that all Android apps interact with the Android OS. We will see the phases of the lifecycle that an app goes through, from creation to destruction, and how this helps us know where to put our Java code, depending on what we are trying to achieve. Chapter 7, Java Variables, Operators, and Expressions, covers the core fundamentals of Java: the code that goes into the classes and the methods that we create, along with the data that the code acts upon. In this chapter, we will focus on the data. We will dive into learning how to write our very own Java code. By the end of the chapter, you will be comfortable writing Java code that creates and uses data within Android.Telegram Channel @IRFaraExamPreface xvChapter 8, Java Decisions and Loops, explains how we can take a course of action dependent upon the value of a variable. We will look at making decisions in Java with if, else, and switch. We will also look at loops in Java with while, do – while, for, and break.Chapter 9, Learning Java Methods, takes a closer look at methods, because although we know that you can call them to make them execute their code, there is moreto them than we have discussed hitherto. Chapter 10, Object-Oriented Programming, explains how in Java, classes are fundamental to just about everything. We will begin to understand why the software engineers at Sun Microsystems back in the early 1990s made Java the way they did. We have already talked about reusing other people's code, specifically the Android API, but in this chapter, we will really get to grips with how this works and learn about object-oriented programming and how to use it.Chapter 11, More Object-Oriented Programming, is the second part of our whirlwind tour (theoretical and practical) into OOP. We have already briefly discussed the concepts of encapsulation, inheritance, and polymorphism, but in this chapter, we will get to see them in action in some demo apps. While the working examples will show these concepts in their simplest forms, it will still be a significant stepping stone toward taking control of our XML layouts via our Java code.Chapter 12, The Stack, the Heap, and the Garbage Collector, reveals the missing link between Java and our XML layouts, leaving us with the power to add all kinds of widgets to our apps, as we have done before, but this time we will be able to control them through our Java code. In this chapter, we will get to take control of some fairly simple UI elements, such as Button and TextView. To enable us to understand what is happening, we need to find out a bit more about the memory in an Android device and two areas of it—the Stack and the Heap.Chapter 13, Anonymous Classes – Bringing Android Widgets to Life, explains how, now that we have a good overview of both the layout and coding of an Android app, as well as our newly acquired insight into object-oriented programming and how we can manipulate the UI from our Java code, we are ready to experiment with more widgets from the palette alongside anonymous classes. In this chapter, we will diversify a lot by going back to the Android Studio palette and looking around at half a dozen widgets that we have either not seen at all or have not used fully yet. Once we have done so, we will put them all into a layout and practice manipulating them with Java code.Telegram Channel @IRFaraExamxvi PrefaceChapter 14, Android Dialog Windows, covers how to present the user with a pop-up dialog window. We can then put all that we know into the first phase of our first major app, Note to self. We will also then learn about new Android and Java features in this chapter and the four following (up to chapter 18), and then use our newly acquired knowledge to enhance the Note to self app each time. In each chapter, we will also build a selection of smaller apps that are separate from this main app. Chapter 15, Arrays, Maps, and Random Numbers, talks about Java arrays, which allow us to manipulate a potentially huge amount of data in an organized and efficient manner. We will also use a close Java relation to arrays, the ArrayList, and see the differences between them. Once we are comfortable handling substantial amounts of data, we will see what the Android API has in order to help us easily connect our new-found data handling skills to the UI without breaking sweat.Chapter 16, Adapters and Recyclers, first covers the theory of adapters and lists. We will learn how to extend RecyclerAdapter in Java code and add a RecyclerView, which acts as a list to our UI, and then, through the apparent magic of the Android API, bind them together so that RecyclerView displays the contents of RecyclerAdapter and allows the user to scroll through the contents.Chapter 17, Data Persistence and Sharing, examines a couple of different ways to save data to the Android device's permanent storage. Also, for the first time, we will add a second activity to our app. It often makes sense when implementing a separate "screen", such as a settings screen in our app, to do so in a new activity. We will see how to add an activity and navigate the user between them.Chapter 18, Localization, explains how to add additional languages. We will see how adding text the correct way via String resources benefits us when it comes to adding multiple languages.Chapter 19, Animations and Interpolations, covers how we can use the Animation class to make our UI a little less static and a bit more interesting. As we have come to expect, the Android API will allow us to do some quite advanced things with relatively straightforward code, and the Animation class is no different.Chapter 20, Drawing Graphics, is devoted to the Android Canvas class and a number of related classes, such as Paint, Color, and Bitmap. These classes combined bring great power when it comes to drawing to the screen. If we want to make a drawing app, draw graphs, or perhaps a game, we need to take control of every pixel that the Android device has to offer.Telegram Channel @IRFaraExamPreface xviiChapter 21, Threads and Starting the Live Drawing App, gets started on the next app. This app will be a kid's style drawing app where the user can draw on the screen with their finger. This drawing app will be slightly different, however. The lines that the user draws will comprise particle systems that explode into thousands of pieces. We will call the project Live Drawing.Chapter 22, Particle Systems and Handling Screen Touches, explains how to create the entities that will exist and evolve in this real-time system as if they have a mind of their own and form the appearance of the drawings that the user can achieve. We will also see how the user draws these entities by learning how to respond to interaction with the screen. This is different to interacting with a widget in a UI layout.Chapter 23, Supporting Different Versions of Android, Sound Effects, and Spinner Widget, explains how we can detect and handle different versions of Android. We will then be able to study the SoundPool class and the different ways we use it, depending on the Android version the app is running on. At this point, we can then put everything we have learned into producing a cool sound demo app that will also introduce us to a new UI widget – the Spinner.Chapter 24, Design Patterns, Multiple Layouts, and Fragments, is more about your future apps than anything in the book so far. We will look at a few aspects of Java and Android that you can use as a framework or template for making ever more exciting and complex apps at the same time as keeping the code manageable. Furthermore, I will suggest areas of further study that there is simply not enough room to even scratch the surface of in this book.Chapter 25, Building a Simple Image Gallery App, explains how to create an app using paging and swiping with images as you might find in a photo gallery app. Also, using the RecyclerView widget, we will selectively load just the data required for the current page and perhaps the data for the previous and next pages.Chapter 26, Advanced UI with Navigation Drawer and Fragment, covers what is (arguably) the most advanced UI. NavigationView can be created simply by choosing it as a template when you create a new project. We will then examine the autogenerated code and learn how to interact with it. Then, we will use all we know about Fragment to populate each of the "drawers" with different behaviors and views. Chapter 27, Android Databases, explains how, if we are going to make apps that offer our users significant features, then almost certainly we are going to need a way to manage, store, and filter significant amounts of data. JSON and SharedPreferences classes have their place but, at some point, we need to move on to using real databases for real-world solutions. Android uses the SQLite database management system and, as you would expect, there is an API to make it as easy as possible.Telegram Channel @IRFaraExamChapter 28, A Quick Chat Before You Go, brings our journey to an end. This chapteris simply includes a few ideas and pointers that you might like to look at before rushing off and making your own apps.To get the most out of this bookTo succeed with this book, you don't need any experience whatsoever. If you are confident with your operating system of choice (Windows, macOS, or Linux), you can learn to make Android apps while learning the Java programming language. Learning to develop professional quality apps is a journey that anybody can embark upon and stay on for as long as they want.If you do have previous programming (Java or any other language), Android, or other development experience, then you will make faster progress with the earlier chapters.If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.Download the example code filesYou can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!Download the color imagesWe also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781800563438_ColorImages.pdf.Telegram Channel @IRFaraExamhttps://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Editionhttps://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Editionhttps://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Editionhttps://github.com/PacktPublishing/https://static.packt-cdn.com/downloads/9781800563438_ColorImages.pdfhttps://static.packt-cdn.com/downloads/9781800563438_ColorImages.pdfPreface xixConventions usedThere are a number of text conventions used throughout this book.Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Th last member variable is a LayoutInflater instance, which will be used to inflate each of the instances of pager_item.xml."A block of code is set as follows:@Overridepublic int getCount() { return images.length;}When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager.widget.PagerAdapter;import androidx.viewpager.widget.ViewPager;Any command-line input or output is written as follows:$ mkdir css$ cd cssBold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."Tips or important notes Appear like this.Telegram Channel @IRFaraExamGet in touchFeedback from our readers is always welcome.General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com.Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.ReviewsPlease leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!For more information about Packt, please visit packt.com.Telegram Channel @IRFaraExamhttp://www.packtpub.com/support/erratahttp://authors.packtpub.comhttp://authors.packtpub.comhttp://packt.com1Beginning Android and JavaWelcome to Android Programming for Beginners Third Edition. In this first chapter, we won't waste any time getting started with developing Android apps. We will look at what is so great about Android, what exactly Android and Java are, how they work and complement each other, and what that means to us as future developers. Moving quickly on, we will set up the required software so we can build and deploy a simple first app.NoteIt is my aim to keep this book up to date. Please check the following web page for any discussion and tips on any changes to Android Studio since the book was first printed: http://gamecodeschool.com/books/android-programming-for-beginners-3rd-edition#android-studio-updates.By the end of this chapter, we will have done the following:• Discovered what is new in this third edition• Learned how Java and Android work together• Set up our development environment – Android Studio – which takes care of all the components involved in building the Android apps that we will learn about nextTelegram Channel @IRFaraExamhttp://gamecodeschool.com/books/android-programming-for-beginners-3rd-edition#android-studio-updateshttp://gamecodeschool.com/books/android-programming-for-beginners-3rd-edition#android-studio-updateshttp://gamecodeschool.com/books/android-programming-for-beginners-3rd-edition#android-studio-updates2 Beginning Android and Java• Learned about the Java Development Kit (JDK) and the Android Application Programming Interface (API) and how we use them through Android Studio• Built our very first Android app• Deployed the app on an Android emulator • Run our app on an Android emulator and a real deviceThat's a lot to get through, so let's get started.Technical requirementsThe following are the official technical requirements for Android development with Android Studio and its related tools. However, these are the absolute bare minimum. Please see the Setting up Android Studio section for further details.The requirements for Windows are as follows:• Microsoft® Windows® 7/8/10 (64-bit)• 4 GB RAM as a minimum; 8 GB RAM recommended• 2 GB of available disk space as a minimum; 4 GB recommended (500 MB for the Integrated Development Environment (IDE) + 1.5 GB for the Android Software Development Kit (SDK) and emulator system image)• 1,280 x 800 minimum screen resolutionThe requirements for Mac are as follows:• Mac® OS X® 10.10 (Yosemite) or higher, up to 10.14 (macOS Mojave)• 4 GB RAM as a minimum; 8 GB RAM recommended• 2 GB of available disk space as a minimum; 4 GB recommended (500 MB for the IDE + 1.5 GB for the Android SDK and emulator system image)• 1,280 x 800 minimum screen resolutionThe requirements for Linux are as follows:• GNOME or KDE desktop• Tested on gLinux based on Debian• 64-bit distribution capable of running 32-bit applications• GNU C Library (glibc) 2.19 or laterTelegram Channel @IRFaraExamWhat's new in the third edition? 3• 4 GB RAM as a minimum; 8 GB RAM recommended• 2 GB of available disk space as a minimum; 4 GB recommended (500 MB for the IDE + 1.5 GB for the Android SDK and emulator system image)• 1,280 x 800 minimum screenresolutionYou can find the code files present in this chapter on GitHub at https://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Edition/tree/main/chapter%2001.What's new in the third edition?The second edition saw huge amounts of additional topics compared to the first edition. Unfortunately, there are only so many pages that can fit in a paperback book. Therefore, this edition focuses on improving the way that the Java, Android, and app development concepts are taught. We have rethought the way that topics are explained and made it more visual than before. In addition, I have managed to squeeze in about a dozen new mini topics. These are either Java fundamentals such as variable types not covered in earlier editions, new Android Studio features such as the profiler, or classic programming concepts such as method recursion and the live debugging of our code. Hopefully, this third edition will therefore make your Android and Java journeys smoother and more complete.Why Java and Android?When Android first arrived in 2008, it was a bit drab compared to the much more stylish iOS on the Apple iPhone/iPad. But quite quickly, through diverse handset offerings that struck a chord with both the practical price-conscious as well as the fashion-conscious and tech-savvy, the Android user numbers exploded.For many, myself included, developing for Android is the most rewarding pastime and business bar none. Quickly putting together a prototype of an idea, refining it, and then deciding to run with it and wire it up into a fully fledged app is such an exciting and rewarding process. Any programming can be fun, and I have been programming all my life, but creating for Android is somehow extraordinarily rewarding. Telegram Channel @IRFaraExamhttps://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Edition/tree/main/chapter%2001https://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Edition/tree/main/chapter%2001https://github.com/PacktPublishing/Android-Programming-for-Beginners-Third-Edition/tree/main/chapter%20014 Beginning Android and JavaDefining exactly why this is the case is quite difficult. Perhaps it is the fact that the platform is free and open source. You can distribute your apps without needing the permission of a big, controlling corporation – nobody can stop you. At the same time, you have well-established, corporate-controlled mass markets such as Amazon Appstore and Google Play.More likely, the reason why developing for Android gives such a good feeling is the nature of the devices themselves. They are deeply personal. You can develop apps that interact with people's lives – educate, entertain, tell a story, and so on – and it is there in their pockets ready to go, in the home, in the workplace, or on holiday. You can certainly build something bigger for the desktop. But knowing that thousands (or millions) of people are carrying your work in their pockets and sharing it with friends gives more than just a buzz. In fact, developing for Android is considered highly skillful and the most successful developers are hugely admired, even revered.If all this fluffy and spiritual stuff doesn't mean anything to you, then that's fine too; developing for Android can make you a living or even make you wealthy. With the continued growth of device ownership, the ongoing increase in CPU and GPU power, and the non-stop evolution of the Android operating system itself, the need for professional app developers is only going to grow. In short, the best Android developers – and, more importantly, the Android developers with the best ideas and most determination – are in greater demand than ever. Nobody knows who these future Android app developers are and they might not even have written their first line of Java yet.So, why isn't everybody an Android developer? Obviously, not everybody will share my enthusiasm for the thrill of creating software that can help people make their lives better, but I am guessing that because you are reading this, you might!The beginner's first stumbling blockUnfortunately, for those that do share my enthusiasm, there is a kind of glass wall on the path of progress that frustrates many aspiring Android developers.Android uses Java to make apps. Every Android book, even those aimed at so-called beginners, assumes readers have at least an intermediate level of Java knowledge, and most need an advanced level. So, good-to-excellent Java knowledge was a prerequisite for learning Android.Telegram Channel @IRFaraExamHow Java and Android work together 5Unfortunately, learning Java in a completely different context to Android can sometimes be a little dull and much of what you learn is not directly transferable to the world of Android anyway. You can see why beginners to Android and Java are often put off from starting.But it doesn't need to be like this. In this book, I have carefully placed all the Java topics you would learn in a thick and weighty Java-only beginner's tome and reworked them into four multi-chapter apps and more than a dozen quick mini-apps, starting from a simple memo app and then progressing to a cool drawing app, a database app, and a playable game (available online).If you want to become a professional Android developer or just want to have more fun when learning Java and Android, this book will help. How Java and Android work togetherBefore we start our Android quest, we need to understand how Android and Java work together. Android is a complex system, but you do not need to understand it in depth to be able to make amazing apps. After we write a program in Java for Android, we click a button and our code is transformed into another form, the form that is understood by Android. This other form is called bytecode and the transformation process is called compiling. Then, when the user installs our application, the bytecode is translated by another process known as the Android Runtime (ART) into machine code. This is the fastest possible execution format. So, if you have ever heard people saying that you shouldn't use Java because it is slow, then you know they are mistaken. Java is fast for the programmer to program and is then, upon installation, changed to machine code that is fast for the device. What could be better?Not only does ART enable super-fast execution of our apps, but it also lowers battery use. Furthermore, the ART system doesn't just create the machine code and then sit back and relax; it provides hooks into our application that enhance memory management while the application is running. This makes our app run more efficiently and, as we will see in Chapter 12, The Stack, the Heap, and the Garbage Collector, easier to write by handling critical aspects of memory management.The ART itself is a software system written in another language that runs on a specially adapted version of the Linux operating system. So, what the user sees of Android is itself just an app running on yet another operating system. Telegram Channel @IRFaraExam6 Beginning Android and JavaAndroid is a collection of sub-systems. The typical Android user doesn't see the Linux operating system or know anything of the presence of ART but they are both there making things tick.The purpose of the Linux part of the system is to hide the complexity and diversity of the hardware and software that Android runs on, but at the same time exposing all its useful features. This exposing of features works in two ways:• First, the system itself must have access to the hardware, which it does.• Second, this access must be programmer-friendly and easy to use – and this is because of the Android API.Let's continue by talking more about the Android API.NoteThis book is about learning Java and building Android apps from scratch, so I won't go any deeper than I have into how Android works. If,however, you want to know more, then the Wikipedia page is a good reference: https://en.wikipedia.org/wiki/Android_(operating_system).Understanding the Android APIThe Android API is code that makes it easy to do exceptional things. A simple analogy could be drawn with a machine, perhaps a car. When you press on the accelerator, a whole bunch of things happen under the hood. We don't need to understand combustion or fuel pumps because some smart engineer has made an interface for us – in this case, a mechanical interface: the accelerator pedal.For example, the following line of Java code probably looks a little intimidating at this stage in the book, but it serves as a good example of how the Android API helps us: locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)Once you learn that this single line of code searches for available satellites in space, and then communicates with them in their orbits around the Earth, then retrieves your precise latitude and longitude on the surface of the planet, it becomes easy to begin to glimpse the power and depth of the Android API in conjunction with the compiled bytecode and ART. For sure, that code does look a little challenging – even mind-boggling at this stage of the book – but imagine trying to talk to a satellite some other way!Telegram Channel @IRFaraExamhttps://en.wikipedia.org/wiki/Android_(operating_systemhttps://en.wikipedia.org/wiki/Android_(operating_systemHow Java and Android work together 7The Android API has a whole bunch of Java code that has already been written for us to use as we like. NoteThere are many different estimates of the number of lines of code that have gone into Android. Some estimates are as low as 1 million, while some are as high as 20 million. What might seem surprising is that despite this vast amount of code, Android is known in programming circles for being "lightweight."The question we must ask and the one this book tries to answer is as follows:How do we use all this code to do cool stuff? Or to frame the question to fit the earlier analogy, how do we find and manipulate the pedals, steering wheel, and sunroof of the Android API? The answer to this question is the Java programming language and the fact that Java was designed to help programmers handle complexity. Let's talk a bit about Java and Object-Oriented Programming (OOP).Java is object-orientedJava is a programming language that has been around a lot longer than Android. It is an object-oriented language. This means it uses the concept of reusable programming objects. If this sounds like technical jargon, another analogy will help. Java enables us and others (such as the Android development team) to write Java code that can be structured based on real-world things, and here is the important part: it can be reused. So, using the car analogy, we could ask the question: if a manufacturer makes more than one car in a day, do they redesign every part for each and every car? The answer, of course, is no. They get highly skilled engineers to develop exactly the right components, honed, refined, and improved over years. Then, that same component is reused again and again as well as being occasionally improved. If you are going to be fussy about my analogy, then you can point out that each of the car's components still has to be built from the raw materials using real-life engineers or robots and so on.This is true. What software engineers do when they write their code is build a blueprint for an object. We then create an object from their blueprint using Java code and once we have that object, we can configure it, use it, combine it with other objects, and more besides. Telegram Channel @IRFaraExam8 Beginning Android and JavaFurthermore, as well as this, we can design blueprints ourselves and make objects from them as well. The compiler then transforms (manufactures) our bespoke creation into bytecode. Hey, presto! We have an Android app.In Java, a blueprint is called a class. When a class is transformed into a real working "thing," we call it an object or an instance of the class.Objects conciselyWe could go on making analogies all day long. All we care about at this point, however, is the following.Java is a language that allows us to write code once that can then be used repeatedly. This is very useful because it saves us time and allows us to use other people's code to perform tasks we might otherwise not have the time or knowledge to write ourselves. Most of the time, we do not even need to see this code or even know how it works! One last analogy: we just need to know how to use the code just as we need to learn how to drive a car.So, some smart software engineer up at Android HQ writes a desperately complex Java program that can talk to satellites. They then consider how they can make this code useful to all the Android programmers who want to make amazing apps that use the user's location to do cool things. One of the things they will do is make features such as getting the device's location in the world a simple one-line task. So, the one line of code we saw previously sets in action many more lines of code that we don't see and don't need to see. This is an example of using somebody else's code to make our code infinitely simpler. NoteIf the fact that you don't have to see all the code is a disappointment to you, then I understand how you feel. Some of us, when we learn about something, want to learn every intricate detail. If you are like this, then be reassured that the best place to start learning how the Android API works internally is to use it as the API programmers intended. Throughout the book, I will regularly point out further learning opportunities where you can find out about the inner workings of the Android API. Also, we will be writing classes that are themselves reusable, kind of like our own API, except that our classes will focus on what we want our app to do.Welcome to the world of object-oriented programming – OOP. I will constantly refer to OOP in every chapter and there is the big reveal of how it works in Chapter 10, Object-Oriented Programming.Telegram Channel @IRFaraExamHow Java and Android work together 9Run that by me again – what exactly is Android?To get things done on Android, we write Java code of our own, which also uses the Java code of the Android API. This is then compiled into bytecode and translated by ART when installed by the user into machine code, which in turn has connections to an underlying operating system called Linux, which handles the complex and extremely diverse range of hardware that are the different Android devices.The manufacturers of the Android devices and the individual hardware components obviously know this too and they write advanced software called drivers, which ensure that their hardware (CPU, GPU, GPS receivers, memory chips, hardware interfaces, and so on) can run on the underlying Linux operating system.The bytecode (along with some other resources) is placed in a bundle of files called an Android Application Package (APK) and this is what ART needs to run to prepare our app for the user.NoteIt is not necessary to remember the details of the steps that our code goes through when it interacts with the hardware. It is enough just to understand that our Java code goes through some automated processes to become the apps that we will publish to the Google Play Store.The next question is "where exactly does all this Java coding and compiling into bytecode along with APK packaging take place?". Let's look at the development environment we will be using.Android StudioA development environment is a term that refers to having everything you need to develop, set up, and be ready to go in one place. We need two things to get started:• We talked a fair bit about compiling our Java code, as well as other people's Java code,into bytecode that in turn will be converted into executable machine code on the user's Android device. To use Java code, we need some free software called the JDK. The JDK includes even more of other people's code, which is separate from the Android API. • There is an entire range of tools needed to develop for Android, and we also need the Android API, of course. This whole suite of requirements is collectively known as the Android SDK. Fortunately, downloading and installing a single application will give us these things all bundled together. The application is called Android Studio.Telegram Channel @IRFaraExam10 Beginning Android and JavaAndroid Studio is an IDE that will take care of all the complexities of compiling our code and linking with the JDK and the Android API. Once we have installed Android Studio, we can do everything we need inside this single application and put to the back of our minds many of the complexities we have been discussing.TipOver time, these complexities will become second nature. It is not necessary to master them to make further progress.So, we had better get hands-on with Android Studio.Setting up Android StudioSetting up Android Studio is quite straightforward if a little lengthy. Grab some refreshments and get started with the following steps. This tutorial will install Android Studio to the D drive. I chose the D drive because it is a big install, around 12 GB once we have everything downloaded, and the D drive on many PCs is typically larger and has more free space than the C drive. Should you wish to install on the C drive (or any other drive), then these instructions should be easy to adjust:1. Visit https://developer.android.com/studio and click the Download Android Studio button. This will begin the download of the latest stable version for Windows. You will need to accept the terms and conditions to commence the download.2. While you are waiting for the download to complete, create a new folder on the root of your D drive called Android. Inside the Android folder, create another new folder called Android Studio. Navigate back to the Android folder and create another new folder named Projects. This is where we will keep all the project files we will create throughout the book. Create another new folder called Sdk, which is where we will ask the installer program to install the Android SDK. You should now have a D:\Android folder that looks like this:Figure 1.1 – D:\Android folderTelegram Channel @IRFaraExamhttps://developer.android.com/studioSetting up Android Studio 113. Once the download is complete, find the downloaded file. It will be called android-studio-ide .... Double-left-click the file to run it.4. You will be asked to grant the installer program administrative privileges, then you can left-click Next to begin the installation. On the Choose Components screen, make sure that both the Android Studio and Android Virtual Device options are checked, and then left-click the Next button:Figure 1.2 – Choose Components screen5. On the Configuration Settings window, left-click the Browse button and navigate to D:\Android\Android Studio, and then left-click the OK button:Figure 1.3 – Configuration Settings windowTelegram Channel @IRFaraExam12 Beginning Android and Java6. Left-click the Next button shown in the preceding screenshot. On the Choose Start Menu Folder window, left-click Install to accept the default option. The first part of the installation will now proceed.7. Once you get the Installation Complete message, left-click the Next button. You can then left-click the Finish button. Android Studio should start automatically. If it doesn't, you can find and start the Android Studio app from your Windows start menu.8. You will be prompted that you have a missing SDK (unless this is not the first time you have used Android Studio). Left-click Next to continue.9. On the SDK Components Setup screen shown next, we want to change the install location. Left-click the Android SDK Location field and browse to D:\Android\Sdk, as shown in the following screenshot:Figure 1.4 – SDK Components Setup screen10. Left-click the Next button.11. On the Verify Settings window, left-click the Finish button. Android Studio will now download some more files and complete the installation. It could take a few minutes or more and you might again be prompted to allow access to your PC. 12. When the process is over, left-click the Finish button.Telegram Channel @IRFaraExamWhat makes an Android app? 13You will be greeted with the Android Studio welcome screen, shown next:Figure 1.5 – Android Studio welcome screenIf you are carrying straight on with the next section, then leave this screen up. If you want, you can close it down and run Android Studio from the Windows start menu, just like any other app, when you are ready to proceed.Let's talk about all the different things that an Android app comprises.What makes an Android app?We already know that we will write Java code that will itself use other people's Java code and will be compiled into bytecode that is converted into machine code on our users' Android devices. In addition to this, we will also be adding and editing other files that are included in the final APK as well. These files are known as Android resources.Android resourcesOur app will include resources such as images, sound, and User Interface (UI) layouts, which are kept in separate files from the Java code. We will slowly introduce ourselves to them over the course of the book.Telegram Channel @IRFaraExam14 Beginning Android and JavaIt will also include files that have the textual content of our app. It is the convention to refer to the text in our app through separate files because it makes them easy to change and easy to create apps that work for different languages and geographical regions.Furthermore, the actual UI layout of our apps, despite the option to implement them with a visual designer, is actually read from text-based files by Android.Android (or any computer), of course, cannot read and recognize text in the same way that a human can. Therefore, we must present our resources in a highly organized and predefined manner. To do so, we will use eXtensible Markup Language (XML). XML is a huge topic but fortunately, its whole purpose is to be both human- and machine-readable. We do not need to learn this language; we just need to note (and then conform to) a few rules. Furthermore, most of the time that we interact with XML, we do so through a neat visual editor provided by Android Studio. We can tell when we are dealing with an XML resource because the filename will end with the extension .xml.You do not need to memorize this as we will constantly be returning to this concept throughout the book.The structure of Android's Java codeIn addition to these resources, it is worth noting that Java as used in Android has a structure to its code. There are many millions of lines of code that we can take advantage of. This code will obviously need to be organized in a way that makes it easy to find and refer to. It is organized into packages that are specific to Android. PackagesWhenever we create a new Android app, we will choose a unique name known as a package. We will see how we do this in the Building our first Android app section. Packages are often separated into sub-packages, so they can be grouped together with other similar packages. We can simply think of this as folders and sub-folders, which is almost exactly what it is.Telegram Channel @IRFaraExamThe structure of Android's Java code 15We can think of all the packages that the Android API makes available to us as code from a code library. Some common Android packages we will use include the following:• android.graphics• android.database• android.view.animationAs you can see, they are arrangedand named to make what is in them as obvious as possible.NoteIf you want to get an idea of the sheer depth and breadth of the Android API, then look at the Android package index: https://developer.android.com/reference/packages.ClassesEarlier, we learned that the reusable code blueprints that we can transform into objects are called classes. Classes are contained in these packages. We will see in our very first app how we can easily import other people's packages along with specific classes from those packages for use in our projects. A class will almost always be contained in its own file with the same name as the class and it will also have the .java file extension.MethodsIn Java (and therefore Android), we further break up our classes into sections that perform the different actions of our class. We call these action-oriented sections methods. It is most often the methods of the class that we will use to access the functionality provided within all those millions of lines of code. We do not need to read the code. We just need to know which class has what we need, which package it is in, and which methods from within the class give us precisely the result we are after. The next diagram shows a representation of the Android API. The structure of the code we will be writing will be similar to the way this example is structured, although we will usually have just one package per app. Telegram Channel @IRFaraExamhttps://developer.android.com/reference/packageshttps://developer.android.com/reference/packages16 Beginning Android and JavaOf course, because of the object-oriented nature of Java, we will only be using selected parts from this API. Notice also that each class has its own distinct data. Typically, if you want access to the data in a class, you need to have an object of that class:Figure 1.6 – A representation of the Android APIYou do not need to memorize this as we will constantly be returning to this concept throughout the book.By the end of this chapter, we will have imported multiple packages, as well as dozens of classes from them, and we will have used many of their methods as well. By the end of Chapter 2, First Contact: Java, XML, and the UI Designer, we will have even written our very own methods. Now we can get started with the first app.Building our first Android appIn programming, it is tradition for the first app of a new student to use whatever language/operating system they are using to say hello to the world. We will quickly build an app that does just that and in Chapter 2, First Contact: Java, XML, and the UI Designer, we will go beyond that and add some buttons that respond to the user when they are pressed.Telegram Channel @IRFaraExamBuilding our first Android app 17NoteThe complete code as it stands at the end of this chapter is in the download bundle in the Chapter 1 folder for your reference. You can't simply copy and paste this code, however! You still need to go through the project creation phase explained in this chapter (and at the beginning of all the projects) as Android Studio does lots of work behind the scenes. Once you become familiar with these steps and understand which code is typed by you the programmer and which code/files are generated by Android Studio, you will then be able to save time and typing by copy and pasting the files I supply in the download bundle.Follow these steps to start the project:1. Run Android Studio in the same way you run any other app. On Windows 10, for example, the launch icon appears in the start menu.TipIf you are prompted with Import Studio settings from…, choose Do not import settings.2. You will be greeted with the Android Studio welcome screen, as shown in the following screenshot. Locate the start a new Android Studio project option and left-click it:Figure 1.7 – Android Studio welcome screenTelegram Channel @IRFaraExam18 Beginning Android and Java3. The window that follows is Select a Project Template. These are some useful project templates that Android Studio can generate for you depending on the type of app you are going to develop. We will use the Basic Activity option. Android Studio will auto-generate a small amount of code and a selection of resources to get our project started. We will discuss the code and the resources in detail in the next chapter. 4. Select Basic Activity. Here is a picture of the Select a Project Template window with the Basic Activity option selected:Figure 1.8 – Select a Project Template window5. Make sure Basic Activity is selected as it is in the preceding screenshot, and then click Next.Telegram Channel @IRFaraExamBuilding our first Android app 196. After this, Android Studio will bring up the Configure Your Project window. This is where we will do the following:a. Name the new project. b. Choose where on our computer the project files should go. c. Provide a package name to distinguish our project from any others in case we should ever decide to publish the app on the Play Store.d. Select the programming language we will use. The name of our project is going to be Hello World and the location for the files will be your Projects folder that we created in the Setting up Android Studio section.The package name can be almost anything you like. If you have a website, you could use the format com.yourdomainname. If not, feel free to use my domain name, com.gamecodeschool.helloworld, or something that you just make up yourself. It is only important when you come to publish. To be clear, in case you can't see the details in the following screenshot clearly, here are the values I used. Remember that yours might vary depending upon your choices for package name and project location:TipNote that the application name has a space between Hello and World but the project location does not and will not work if it does.Telegram Channel @IRFaraExam20 Beginning Android and Java7. The next screenshot shows the Configure Your Project screen once you have entered all the information:Figure 1.9 – Configure Your Project screen8. In the previous screenshot, you can see that Android Studio has auto-generated a package name based on the information entered. Mine is com.gamecodeschool.helloworld. Yours might be the same or not; it doesn't matter. NoteYou can write Android apps in a few different languages, including C++ and Kotlin. There are various advantages and disadvantages to each compared to using Java. Learning Java will be a great introduction to other languages and Java is also an official language of Android. Most top apps and games on the Play Store are currently written in Java. You can also see the Minimum SDK option. Leave this at the default but note that the default might be different for you at the time of writing.Telegram Channel @IRFaraExamDeploying the app so far 21NoteWe already know that the Android SDK is the collection of packages of code that we will be using to develop our apps. Like any good SDK, the Android SDK is regularly updated and each time it gets a significant update, the version number is increased. Simply put, the higher the version number, the newer the features you get to use; the lower the version number, the more devices our app will work on. For now, Android Jelly Bean will give us lots of great features and near-100% compatibility with the Android devices currently in use. If at the time of reading Android Studio is suggesting a newer API and Android version, then go with that.If you are reading this some years in the future, then the Minimum SDK option will probably default to something different but the code in this book will still work.9. Click the Finish button and we will run the app to see what we have achieved.NoteThe first time you create a new project, Android Studio will initiate another download. Android Studio will set up the Gradle buildsystem that it uses to manage project configuration and deployment. This will only happen for the first project. No knowledge of Gradle is required for the book but if you are curious, a simple web search will reveal more.Let's look at our app in action.Deploying the app so farBefore we explore any of the code and learn our first bit of Java, you might be surprised to learn that we can already run our project. It will just be a fairly featureless app but as we will be running the app as often as possible to check our progress, let's see how to do that now. You have three options:• Run the app on the emulator on your PC (part of Android Studio) in debug mode.• Run the app on a real Android device in USB debugging mode.• Export the app as a full Android project that can be uploaded to the Play Store.Telegram Channel @IRFaraExam22 Beginning Android and JavaThe first option (debug mode) is the easiest to set up because we did it as part of setting up Android Studio. If you have a powerful PC, you will hardly notice the difference between the emulator and a real device. However, screen touches are emulated by mouse clicks and proper testing of the user's experience is not possible in some of the later apps we will create, such as the drawing app. Furthermore, you might just prefer to test out your creations on a real device occasionally – I know I do.The second option, using a real device, has a couple more steps but once set up is as good as option 1 and the screen touches are for real.The final option takes about 5 minutes (at least) to prepare, and then you need to manually put the created package onto a real device and install it every time you make a change to the code.Probably the best way is to use the emulator to quickly test and debug minor increments in your code, and then fairly regularly use USB debugging mode on a real device to make sure things are still as expected. Only occasionally will you want to export an actual deployable package. For these reasons, we will now go through how to run the app using the emulator and USB debugging on a real device. Running and debugging the app on an Android emulatorFollow these simple steps to run the app on the default Android emulator:1. From the Android Studio menu bar, select Tools | AVD Manager. AVD stands for Android Virtual Device (an emulator). You will see the following window:Figure 1.10 – AVD ManagerTelegram Channel @IRFaraExamDeploying the app so far 23Notice there is an emulator on the list. In my case, it is Pixel_3a_API_30_x…. If you are following this sometime in the future, it may be a different emulator that was installed by default. It won't matter.Important NoteThe emulator should have been installed by the steps we have performed previously. I noticed while testing with one pre-release version that it wasn't installed by default. In the event that there is no emulator listed on the Your Virtual Devices screen, select Tools | AVD Manager | Create Virtual Device… | Next| R Download | Accept | Next and a default emulator will be downloaded and installed. When the installation is done, click Finish followed by Next and finally Finish again. Now you can refer to the previous step to run the emulator.2. Click the green play icon (to the right) shown in the next screenshot and wait as the emulator boots up:Figure 1.11 – Play icon3. Now you can click the play icon on the Android Studio quick launch bar as shown in the next screenshot, and if prompted, choose Pixel_3a_API_30_x… (or whatever your emulator is called) and the app will launch on the emulator:Figure 1.12 – Play icon on the Android Studio quick launch barTelegram Channel @IRFaraExam24 Beginning Android and JavaYou're done. Here is what the app looks like so far in the emulator. Remember that you might (probably do) have a different emulator – that's fine:Figure 1.13 – What the app looks like so farClearly, we have more work to do before we move to Silicon Valley and look for financial backing, but it is a good start. The message on the screen is Hello first fragment. A fragment is a building block of many Android apps and we will explore them further throughout the book. If you click on the Next button, you will see a new empty layout, and if you then click on the Previous button, you will see the Hello first fragment screen again. Not bad considering we haven't written any code yet.Telegram Channel @IRFaraExamDeploying the app so far 25We need to test and debug our apps often throughout development to check for any errors, crashes, or anything else unintended. NoteWe will see how we get errors and other feedback for debugging from our apps in the next chapter.It is also important to make sure it looks good and runs correctly on every device type/size that you want to target. Obviously, we do not own one of each of the many thousands of Android devices. This is where emulators come in.Emulators, however, are sometimes a bit slow and cumbersome, although they have improved a lot recently. If you want to get a genuine feel for the experience your users will get, then you can't beat deploying to a real device. So, we will want to use both real devices and emulators while developing our apps.TipIf you are planning on using the emulator again soon, then leave it running to avoid having to wait for it to start again.If you want to try out your app on a tablet, you're going to need a different emulator.Creating a new emulatorIf you want to create an emulator for a different Android device, this is simple. From the main menu, select Tools | AVD Manager. In the AVD Manager window, left-click Create Virtual Device. Now, left-click on the type of device you want to create, TV, Phone, Wear OS, or Tablet. Now, simply left-click Next and follow the instructions to create your new AVD. Next time you run your app, the new AVD will appear as an option to run the app on. We will create a new tablet emulator step by step in the next chapter.Now we can look at how to get our app onto a real device.Running the app on a real deviceThe first thing to do is to visit your device manufacturer's website and obtain and install any drivers that are needed for your device and operating system. Telegram Channel @IRFaraExam26 Beginning Android and JavaNoteMost newer devices won't need a driver. So, you may want to just try the following steps first.The next few steps will set up the Android device for debugging. Note that different manufacturers structure the menu options slightly differently from others. But the following sequence is probably very close, if not exactly the same, for enabling debugging on most devices:1. Tap the Settings menu option or the Settings app on your phone/tablet.2. This next step will vary slightly for different versions of Android. The Developer options menu is hidden away so as not to trouble regular users. You must perform a slightly odd task to unlock the menu option. Tap the About device or About Phone option. Find the Build Number option and repeatedly tap it until you get a message informing you that You are now a developer!.NoteSome manufacturers have different and obscure methods for achieving this step. If this step doesn't work, do a web search for your device and "unlocking developer options."3. Go back to the Settings menu.4. Tap Developer options.5. Tap the checkbox for USB Debugging.6. Connect your Android device to the USB port of your computer.7. Click anywhere on Android Studio to get Android Studio to detect that your device has been connected. You should now find an Allow USB debugging? prompt on your device; hit Allow.8. Click the play icon from the Android Studio toolbar, as shown in the next screenshot:Figure 1.14 – Play icon from the Android Studio toolbar9. When prompted, click OK to run the app on your chosen device.Telegram Channel @IRFaraExam
  • (19) 98773-4238 -Em relação ao tema proposto, e com base nos estudos na disciplina, desenvolva um breve texto, de forma argumentativa, definindo o que são Custos de produção, e como eles se classifica
  • Metodologias Ágeis e Testes
  • Avaliação do Módulo 1M - Introdução à Engenharia de Software_ Revisão da tentativa
  • Falta de apoio à saúde mental socorritores se voltam para os pares
  • Atividade Individual Gerenciamento de Cronograma e Custos
  • Probando Exoplanet Interiors através de simulações de laboratório
  • ORMB - Técnica da Observação da Relação Mamãe-Bebê
  • Uma avaliação experimental aberta de The Number Race, um jogo de computador adaptativo para remediação da discalculia - Tradução
  • Modelo Incremental
  • Introdução à Engenharia de Software
  • b13dfb54-4f6e-4476-bdfe-061775924afe
  • a74f3cb8-add3-4581-809b-b7ef4882d88e
  • c49b3c6a-1b85-4c63-98ec-75696ca7a4da
  • Num projeto de desenvolvimento de software segundo uma metodologia ágil, em qual dos pacotes de trabalho (Work Packages) enquadraria a Engenharia d...
  • Em Eng. de Software, um diagrama do modelo de domínio (escolher quais as afirmações que são verdadeiras)
  • Considere as seguintes afirmações sobre o Humanismo: I. A educação não deve se limitar aos saberes necessários para um exercício profissional espec...
  • DS Em demandas um cenário em que você está gerenciando um software legado que precisa minimizando atuais, qual estratégia de evolução seria mais ap...
  • (11607) Considere o trecho de programa na linguagem Python, onde são previamente conhecidos os valores das variáveis a. b e C. $ main.py > EST 1 a=...
  • Engenharia de Software Arquitetura e Diagrams UML - Modelo de Camadas de uma biblioteca de livros
  • Exemplo de modelo em camadas de um sistema de gerenciamento de uma biblioteca de livros
  • O que são requisitos funcionais e não funcionais? Assinale a alternativa que explica as diferenças. Os funcionais normalmente especificam ou res...
  • O CMMI é O modelo de maturidade criado com o objetivo de proporcionar condições para a evolução das boas práticas de energia de software. Foi desen...
  • Ele representa máquinas e servidores, além de acrescentar os sistemas vistos no diagrama de pacote ou de componentes. Como é chamado esse diagrama?...
  • Quem captura a visão de um sistema físico buscando descrever aspectos estruturais e comportamentais de um software? a.Modelo de software. b.Sis...
  • Limites e derivadas são ferramentas matemáticas úteis, permitindo estudar as características das funções que modelam os fenômenos naturais e os pro...
  • O benefício mais importante proporcionado pelo desenvolvimento baseado em componentes é a reutilização de componentes existentes na construção de n...
  • ENFERMAGEM INFORMATICA Questões de Concursos e Perguntas de Concursos Públicos Aprova Concursos
  • PRF INFORMATICA Questões de Concursos e Perguntas de Concursos Públicos Aprova Concursos

Perguntas dessa disciplina

What courses are offered by Global Mentoring for Java programming? a) Java with JDBC, HTML and CSS, and Android with Java.b) JavaServer Faces, S...
What are some references for learning about ladder logic and automation systems? a. Mayol i Badía, A. (1988). Autómatas programables. Marcombob...
What is the purpose of the document presented? a) To provide a list of volleyball exercises for advanced players.b) To provide a list of volleyb...
android-programming-for-beginners - Engenharia de Software I (2024)

References

Top Articles
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5669

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.