Book Image

Android Programming for Beginners - Second Edition

By : John Horton
Book Image

Android Programming for Beginners - Second Edition

By: John Horton

Overview of this book

Are 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? Or maybe you're just frustrated that in order to learn Android, you must know Java. If so, then this book is for you. This new and expanded second edition of Android Programming for Beginners will be your companion to create Android Pie 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. After 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.
Table of Contents (35 chapters)
Android Programming for Beginners - Second Edition
Contributors
Preface
Other Books You May Enjoy
Index

Preface

Are 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? Or maybe you're just frustrated that to learn Android, you must know Java. If so, then this book is for you.

This new and expanded second edition of Android Programming for Beginners will be your companion to create Android Pie 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.

After 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 for

This 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 advance your knowledge and make rapid progress through the early projects.

What this book covers

Chapter 1, Beginning Android and Java, Welcome to Android Programming for Beginners, Second Edition: In this first chapter, we won't waste any time in getting started 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: By this stage, we have a working Android development environment and we have built and deployed our first app. It is obvious, however, that auto-generated code by Android Studio is not going to make the next top selling app on Google Play. We need to explore this auto-generated code so that we can begin to understand Android and then learn how to build on this useful template

Chapter 3, Exploring Android Studio and the Project Structure: In this chapter, we will create and run two more Android projects. The purpose of these exercises is to explore more deeply Android Studio and the structure of Android projects.

When we build our apps ready for deployment, the code and the resource files need to be packed away in the APK file just so. Therefore, all the layout files and other resources that we will soon discover need to be in the correct structures.

Fortunately, Android Studio handles this for us when we create a project from a template. However, we still need to know how to find and amend these files, how to add our own, and sometimes remove the files created by Android Studio, and how the resource files are interlinked, sometimes with each other, and sometimes with the Java code (auto-generated and our own).

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: We have already seen the Android Studio UI designer, as well as a little bit of Java, in action. In this hands-on chapter, we will build three more layouts—still quite simple, yet a step up from what we have done so far.

Before we get to the hands-on part, we will have a quick introduction to the concept of Material Design.

We will see another type of layout called LinearLayout, and step through it, using it to create a usable UI. We will then take things a step further, using ConstraintLayout, both with understanding constraints, and with designing more complex and precise UI designs. Finally, we will meet the TableLayout, for laying out data in an easily readable table.

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 into one neat parcel.

Chapter 5, Beautiful Layouts with CardView and ScrollView: This 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 met, and we will also introduce two more cool layouts: ScrollView and CardView. To conclude this chapter, we will run the CardView project on a tablet emulator.

Chapter 6, The Android Lifecycle: In this chapter, we will get familiar with the lifecycle of an Android app. At first, this might sound a bit strange, that a computer program has a lifecycle, but it will soon make sense.

The lifecycle is the way that all Android apps interact with the Android OS. Just as the lifecycle of humans interacts with the world around them, we have no choice but to interact with it, and must be prepared to handle different events without notice if we want our apps to survive.

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 out Java code, depending on what we are trying to achieve.

Chapter 7, Java Variables, Operators, and Expressions: In this chapter and the one that follows it, we are going to learn and practice 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 also quickly recap on what we learned in the earlier chapters about Java and then immediately dive into learning how to write our very own Java code. The principles we are about to learn are not limited to Java, but are also applicable to other programming languages as well.

By the end of the chapter, you will be comfortable writing Java code that creates and uses data within Android.

Chapter 8, Java Decisions and Loops: We have just learned about variables and we know how we can change the values that they hold with expressions, but how can we take a course of action dependent upon the value of a variable?

We can certainly add the number of new messages to the number of previously unread messages, but how might we, for example, trigger an action within our app when the user has read all their messages?

The first problem is that we need a way to test the value of a variable and then respond when that value falls within a range of values or is a specific value.

Another problem that is common to all sorts of programming is that we need sections of our code to be executed a certain number of times (more than once or sometimes not at all), depending on the value of variables.

To solve the first problem, we will look at making decisions in Java with if, else, and switch. To solve the latter, we will look at loops in Java with while, dowhile, for, and break.

Chapter 9, Java Methods: As we are starting to get comfortable with Java programming, in this chapter, we will take a closer look at methods, because although we know that you can call them to make them execute their code, there is more to them than we have discussed so far.

Chapter 10, Object-Oriented Programming: In this chapter, we will discover that 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: This chapter 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: By the end of this chapter, the missing link between Java and our XML layouts will be fully revealed, 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, and, in the next chapter, we will take things further and manipulate a whole range of UI elements.

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: This chapter could have been called "Even More OOP", as anonymous classes are very much still part of that subject, but, as we will see, anonymous classes offer us so much flexibility, especially when it comes to interacting with the UI, that I thought they deserved a chapter title dedicated to them and one of their key uses in Android.

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.

OOP is a tricky thing at times, and anonymous classes are known to sometimes be a bit awkward for beginners, but, by gradually learning these new concepts and then practicing them repeatedly, over time they will become our friend.

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.

Chapter 14, Android Dialog Windows: In this chapter, we will see 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, ArrayList, Map and Random Numbers, In this chapter, we will learn 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 user interface without breaking a sweat.

Chapter 16, Adapters and Recyclers: In this brief chapter, we will achieve much. We will first go through the theory of adapters and lists. How we can 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 the RecyclerView displays the contents of the RecyclerAdapter and allows the user to scroll through the contents. You have probably guessed that we will be using this technique to display our list of notes in the Note to Self app.

Chapter 17, Data Persistence and Sharing: In this chapter, we will look at 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", like a settings screen in our app, to do so in a new Activity. We could go to the trouble of hiding the original UI and then showing the new UI, but this would quickly lead to confusing and error-prone code. So, we will see how to add an Activity and navigate the user between them.

Chapter 18, Localization: This chapter is quick and simple, but what we will learn to do here can make your app accessible to millions of more potential users. We will see 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: Here we will see 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: This entire chapter will be about 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. Sometimes, the default UI provided by the Android API isn't what we need. 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.

Chapter 21, Threads, and Starting the Live Drawing App: In this chapter, we will get started on our 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 be comprised of particle systems that explode into thousands of pieces. We will call the project Live Drawing.

Chapter 22, Particle Systems and Handling Screen Touches: We already have our real-time system that we implemented in the previous chapter using a thread. In this chapter, we will 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: In this chapter, we will learn about 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 cool sound demo app that will also introduce us to a new UI widget; the Spinner.

Chapter 24, Design Patterns, Multiple Layouts, and Fragments: We have come a long way since the start when we were just setting up Android Studio. Back then, we went through everything step by step, but, as we have proceeded, we have tried to show not just how to add x to y, or feature a to app b, but to enable you to use what you have learned in your own ways to bring your own ideas to life.

This chapter 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 which there is simply not enough room to even scratch the surface of in this book.

Chapter 25, Advanced UI with Paging and Swiping: Paging is the act of moving from page to page and, on Android, we do this by swiping a finger across the screen. The current page transitions in a direction and speed to match the finger movement. It is a useful and practical way to navigate around an app, but perhaps even more than this, it is an extremely satisfying visual effect for the user. Also, as with RecyclerView, we can selectively load just the data required for the current page and perhaps the data for the previous and following pages.

The Android API, as you would have come to expect, has some solutions for achieving paging in a quite simple manner.

Chapter 26, Advanced UI with Navigation Drawer and Fragment: In this chapter, we will see what is (arguably) the most advanced UI on. The NavigationView, or navigation drawer because of the way it slides out its contents, can be created simply by choosing it as a template when you create a new project. We will do just that and then we will examine the auto-generated 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. Then, in the next chapter, we will learn about databases to add some new functionality to each Fragment.

Chapter 27, Android Databases: 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.

It is possible to store efficiently very large amounts of data with JSON, but when we need to use that data selectively, rather than simply restricting ourselves to the options of "save everything" and "load everything", we need to think about which other options are available.

A good computer science course would probably teach the algorithms necessary to handle sorting and filtering our data, but the effort involved would be quite extensive, and what are the chances of us coming up with a solution that is as good as the people who provide us with the Android API?

As is so often the case, it makes sense to use the solutions provided in the Android API. As we have seen, 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.

Chapter 28, Coding a Snake Game Using Everything We Have Learned So Far: In this bonus and final project, we will use a bit of everything we have leaned throughout the book: interfaces, creating classes, graphics, sound, threads, screen touches, and more.

The history of the Snake game goes back to the 1970s. However, it was the 1980s when the game took on the look that we will be using in this chapter. It was sold under numerous names and many platforms, but probably gained widespread recognition when it was shipped as standard on Nokia mobile phones in the late 1990s.

Chapter 29, Enumerations and Finishing the Snake Game: Welcome to the final practical chapter of the book and the last Java topic. We will first learn about Java enumerations, and then we will put them straight to work in helping us finish the Snake game.

Chapter 30, A Quick Chat Before You Go: We are just about done with our journey. This chapter is just 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 book

  • To 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.

Download the example code files

You can download the example code files for this book from your account at http://www.packt.com. If you purchased this book elsewhere, you can visit http://www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at http://www.packt.com.

  2. Select the SUPPORT tab.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows

  • Zipeg/iZip/UnRarX for Mac

  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Android-Programming-for-Beginners. 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!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: "Now we can turn our attention to the inner class, ListItemHolder."

A block of code is set as follows:

public void showNote(int noteToShow){
   DialogShowNote dialog = new DialogShowNote();
   dialog.sendNoteSelected(noteList.get(noteToShow));
   dialog.show(getSupportFragmentManager(), "");
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public void createNewNote(Note n){
   // Temporary code
   //mTempNote = n;
   noteList.add(n);
   mAdapter.notifyDataSetChanged();
}

Bold: 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: "When you are ready, click the Next > button."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback 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 [email protected].

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, http://www.packt.com/submit-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 [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Reviews

Please 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.