O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Android Programming for Beginners - Second Edition

Book Description

Learn all the Java and Android skills you need to start making powerful mobile applications with practical and actionable steps

Key Features

  • Kick-start your Android programming career, or just have fun publishing apps to the Google Play marketplace
  • A first-principles introduction to Java, via Android, which means you'll be able to start building your own applications from scratch
  • Learn by example and build four real-world apps and dozens of mini-apps throughout the book

Book Description

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.

What you will learn

  • Master the fundamentals of coding Java for Android Pie
  • Install and set up your Android development environment
  • Build functional user interfaces with the Android Studio visual designer
  • Add user interaction, data captures, sound, and animation to your apps
  • Manage your apps' data using the built-in Android SQLite database
  • Find out about the design patterns used by professionals to make top-grade applications
  • Build, deploy, and publish real Android applications to the Google Play marketplace

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 also acts as a refresher for those who already have experience of using Java on Android to advance their knowledge and make fast progress through the early projects.

Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Table of Contents

  1. Android Programming for Beginners - Second Edition
    1. Table of Contents
    2. Android Programming for Beginners - Second Edition
      1. Why subscribe?
      2. Packt.com
    3. Contributors
      1. About the author
      2. About the reviewers
      3. Packt is Searching for Authors Like You
    4. Preface
      1. Who this book is for
      2. What this book covers
      3. To get the most out of this book
        1. Download the example code files
        2. Conventions used
      4. Get in touch
        1. Reviews
    5. 1. Beginning Android and Java
      1. What's new in the second edition?
      2. Why Java and Android?
      3. The beginner's first stumbling block
      4. How Java and Android work together
        1. The Android API
        2. Java is object-oriented
        3. Run that by me again – What exactly is Android?
        4. Android Studio
      5. Setting up Android Studio
        1. Final step – for now
      6. What makes an Android app?
        1. Android resources
      7. The structure of Android's Java code
        1. Packages
        2. Classes
        3. Methods
      8. Our first Android app
        1. Extra step 1
        2. Extra step 2
      9. Deploying the app so far
        1. Running and debugging the app on an Android emulator
        2. Running the app on a real device
      10. Frequently asked questions
      11. Summary
    6. 2. First Contact – Java, XML, and the UI Designer
      1. Examining the log output
        1. Filtering the logcat output
      2. A note for early adopters of this book
      3. Exploring the project's Java code and the main layout's XML code
        1. Examining the HelloWorldActivity.java file
          1. Code folding (hiding) in Android Studio
          2. The package declaration
          3. Importing classes
          4. The class
          5. Methods inside the class
          6. Summary of the Java code so far
        2. Examining the main layout file
          1. UI layout elements
          2. UI text elements
      4. Adding buttons to the main layout file
        1. Adding a button via the visual designer
          1. Editing the button's attributes
        2. Examining the XML code for the new button
        3. Adding a button by editing the XML code
        4. Giving the buttons unique id attributes
        5. Positioning the two buttons in the layout
        6. Making the buttons call different methods
      5. Leaving comments in our Java code
      6. Coding messages to the user and the developer
      7. Writing our first Java code
        1. Adding message code to the onCreate method
          1. Examining the output
        2. Writing our own Java methods
          1. Examining the output
      8. Frequently asked questions
      9. Summary
    7. 3. Exploring Android Studio and the Project Structure
      1. A quick guided tour of Android Studio
      2. Project Explorer and project anatomy
        1. The Empty Activity project
        2. Exploring the Empty Activity project
          1. The manifests folder
          2. The java folder
          3. The res folder
          4. The res/drawable folder
          5. The res/layout folder
          6. The res/mipmap
          7. res/values
            1. The colors.xml file
            2. The strings.xml file
            3. The styles.xml file
        3. The Basic Activity project
        4. Exploring the Basic Activity project
          1. The MainActivity.java file
          2. The activity_main.xml file
          3. The extra methods in MainActivity.java
          4. The content_main.xml file
      3. Exploring the Android emulator
        1. Emulator control panel
        2. Using the emulator as a real device
          1. Accessing the app drawer
          2. Viewing active apps and switching between apps
      4. Summary
    8. 4. Getting Started with Layouts and Material Design
      1. Material design
      2. Exploring Android UI design
      3. Layouts
      4. Creating the Exploring Layouts project
      5. Building a menu with LinearLayout
        1. Adding a LinearLayout to the project
        2. Preparing your workspace
        3. Examining the generated XML
        4. Adding a TextView to the UI
        5. Adding a multi-line TextView to the UI
      6. Wiring up the UI with the Java code (part 1)
      7. Adding layouts within layouts
      8. Making the layout look pretty
      9. Wiring up the UI with the Java code (part 2)
      10. Building a precise UI with ConstraintLayout
        1. Adding a CalenderView
        2. Resizing a view in a ConstraintLayout
        3. Using the Component Tree window
        4. Adding constraints manually
        5. Adding and constraining more UI elements
        6. Making the text clickable
      11. Laying out data with TableLayout
        1. Adding a TableRow to TableLayout
        2. Using the Component Tree when the visual designer won't do
        3. Organizing the table columns
        4. Linking back to the main menu
      12. Summary
    9. 5. Beautiful Layouts with CardView and ScrollView
      1. Attributes quick summary
        1. Sizing using dp
        2. Sizing fonts using sp
        3. Determining size with wrap or match
        4. Using padding and margin
        5. Using the layout_weight property
        6. Using Gravity
      2. Building a UI with CardView and ScrollView
        1. Setting the view with Java code
        2. Adding image resources
        3. Creating the content for the cards
        4. Defining dimensions for CardViews
        5. Adding CardViews to our layout
        6. Including layout files inside another layout
      3. Themes and material design
        1. Using the Android Studio theme designer
      4. Creating a tablet emulator
      5. Frequently asked questions
      6. Summary
    10. 6. The Android Lifecycle
      1. The life and times of an Android app
        1. How Android interacts with our apps
      2. A simplified explanation of the Android lifecycle
        1. The lifecycle phases demystified
      3. How we handle the lifecycle phases
      4. Lifecycle demo app
        1. Coding the lifecycle demo app
        2. Running the lifecycle demo app
        3. Examining the Lifecycle Demo app output
      5. Some other overridden methods
      6. The structure of Java code – revisited
      7. Summary
    11. 7. Java Variables, Operators, and Expressions
      1. Java is everywhere
      2. Syntax and jargon
      3. More code comments
      4. Storing and using data with variables
        1. Types of variables
          1. Primitive types
          2. Reference types
            1. Strings
            2. Arrays
            3. Classes
      5. Using variables
        1. Variable declaration
        2. Variable initialization
        3. Changing values in variables with operators
          1. The assignment operator
          2. The addition operator
          3. The subtraction operator
          4. The division operator
          5. The multiplication operator
          6. The increment operator
          7. The decrement operator
      6. Expressions
        1. Expressing yourself demo app
      7. Summary
    12. 8. Java Decisions and Loops
      1. Making decisions in Java
        1. Indenting code for clarity
        2. More operators
          1. The comparison operator
          2. The logical NOT operator
          3. The NOT equal operator
          4. The greater than operator
          5. The less than operator
          6. The greater than or equal to operator
          7. The less than or equal to operator
          8. The logical AND operator
          9. The logical OR operator
        3. How to use all of these operators to test variables
          1. Using the Java if keyword
            1. Else do this instead
        4. Switching to make decisions
        5. Switch Demo app
      2. Repeating code with loops
        1. While loops
          1. Breaking out of a loop
          2. The continue keyword
        2. Do while loops
        3. For loops
        4. Loops demo app
      3. Summary
    13. 9. Java Methods
      1. Methods revisited
      2. What exactly are Java methods?
      3. Method structure
        1. Modifier
        2. Return type
        3. Name of a method
        4. Parameters
        5. The body
      4. Using methods demo apps
        1. Real world methods
          1. Discovering variable scope
        2. Exploring method overloading
      5. Scope and variables revisited
      6. Frequently asked questions
      7. Further reading
      8. Summary
    14. 10. Object-Oriented programming
      1. Important memory management warning
      2. Object-oriented programming
        1. What is OOP exactly
          1. Encapsulation
          2. Polymorphism
          3. Inheritance
        2. Why do it like this?
        3. Class recap
      3. Looking at the code for a class
        1. Class implementation
        2. Declaring, initializing, and using an object of the class
      4. Basic classes app
        1. More things that we can do with our first class
      5. Frequently asked questions
      6. Summary
    15. 11. More Object-Oriented Programming
      1. Remember that encapsulation thing?
        1. Controlling class use with access modifiers
          1. Class access modifiers
          2. Class access in summary
        2. Controlling variable use with access modifiers
          1. Variable access modifiers
          2. Variable access summary
        3. Methods have access modifiers too
          1. Method access modifiers
          2. Method access summary
        4. Accessing private variables with getters and setters
        5. Setting up our objects with constructors
        6. Static methods
      2. Encapsulation and static methods mini-app
      3. OOP and inheritance
      4. Inheritance example app
      5. Polymorphism
        1. Abstract classes
        2. Interfaces
      6. Frequently asked questions
      7. Summary
    16. 12. The Stack, the Heap, and the Garbage Collector
      1. All the Android UI elements are classes too
        1. Re-introducing references
          1. A quick break to throw out the trash
          2. Seven facts about the Stack and the Heap
        2. So how does this Heap thing help me?
        3. Using Buttons and TextView widgets from our layout
        4. The Inner and Anonymous classes
      2. Frequently asked questions
      3. Summary
    17. 13. Anonymous Classes – Bringing Android Widgets to Life
      1. Declaring and initializing the objects
      2. Creating UI widgets from pure Java without XML
      3. Exploring the palette – part 1
        1. The EditText widget
        2. The ImageView widget
        3. Radio button and group
      4. Anonymous classes
      5. Exploring the palette – Part 2, and more anonymous classes
        1. Switch
        2. CheckBox
        3. TextClock
      6. Widget exploration app
        1. Setting up the widget exploration project and UI
        2. Coding the widget exploration app
          1. Getting a reference to the parts of the UI
          2. Coding the checkboxes
            1. Changing transparency
            2. Changing color
            3. Changing size
          3. Coding the RadioButtons
          4. Using an anonymous class for a regular button
          5. Coding the Switch
        3. Running the Widget Exploration app
      7. Converting layouts to ConstraintLayout
      8. Summary
    18. 14. Android Dialog Windows
      1. Dialog windows
        1. Creating the Dialog Demo project
        2. Coding a DialogFragment class
          1. Using chaining to configure the DialogFragment
        3. Using the DialogFragment class
      2. The Note to self app
        1. Using naming conventions and String resources
        2. How to get the code files for the Note to self app
        3. The completed app
        4. Building the project
        5. Preparing the String resources
        6. Coding the Note class
        7. Implementing the Dialog designs
        8. Coding the dialog boxes
          1. Coding the DialogNewNote class
          2. Coding the DialogShowNote class
        9. Showing our new dialogs
          1. Coding the floating action button
      3. Summary
    19. 15. Arrays, ArrayList, Map and Random Numbers
      1. A random diversion
      2. Handling large amounts of data with arrays
        1. Arrays are objects
      3. Simple array example mini-app
      4. Getting dynamic with arrays
        1. Dynamic array example
      5. Entering the nth dimension with Arrays
        1. Multidimensional Array mini app
        2. Array out of bounds exceptions
      6. ArrayLists
        1. The enhanced for loop
      7. Arrays and ArrayLists are polymorphic
      8. More Java Collections – Meet Java Hashmap
      9. The Note to Self app
      10. Frequently asked questions
      11. Summary
    20. 16. Adapters and Recyclers
      1. RecyclerView and RecyclerAdapter
        1. The problem with displaying lots of widgets
        2. The solution to the problem with displaying lots of widgets
        3. How to use RecyclerView and RecyclerAdapter
        4. What we will do to set up RecyclerView with RecyclerAdapter and an ArrayList of notes
      2. Adding RecyclerView, RecyclerAdapter, and ArrayList to the Note to Self project
        1. Removing the temporary Show Note button and adding the RecyclerView
        2. Creating a list item for the RecyclerView
        3. Coding the RecyclerAdapter class
          1. Coding the NoteAdapter constructor
          2. Coding the onCreateViewHolder method
          3. Coding the onBindViewHolder method
          4. Coding getItemCount
          5. Coding the ListItemHolder inner class
        4. Coding MainActivity to use the RecyclerView and RecyclerAdapter classes
          1. Adding code to onCreate
          2. Modifying the addNote method
          3. Coding the showNote method
      3. Running the app
      4. Frequently asked questions
      5. Summary
    21. 17. Data Persistence and Sharing
      1. Android Intents
        1. Switching Activity
        2. Passing data between Activities
      2. Adding a settings page to Note to Self
        1. Creating the SettingsActivity
        2. Designing the Settings screen layout
        3. Enabling the user to switch to the settings screen
      3. Persisting data with SharedPreferences
      4. Reloading data with SharedPreferences
      5. Making the Note to Self settings persist
        1. Coding the SettingsActivity class
        2. Coding the MainActivity class
      6. More advanced persistence
        1. What is JSON?
        2. Java exceptions – try, catch, and finally
      7. Backing up user data in Note to Self
      8. Frequently asked questions
      9. Summary
    22. 18. Localization
      1. Making the Note to Self app for Spanish, English, and German speakers
        1. Adding Spanish support
        2. Adding German support
        3. Adding the string resources
      2. Running Note to Self in German or Spanish
        1. Making the translations work in Java code
      3. Summary
    23. 19. Animations and Interpolations
      1. Animations in Android
        1. Designing cool animations in XML
          1. Fading in and out
          2. Move it, move it
          3. Scaling or stretching
          4. Controlling the duration
          5. Rotate animations
          6. Repeating animations
          7. Combining animation's properties with Set
        2. Instantiating animations and controlling them with Java code
        3. More animation features
          1. Listeners
          2. Animation interpolators
      2. Animations Demo App – introducing SeekBar
        1. Laying out the animation demo
        2. Coding the XML Animations
        3. Wiring up the Animation Demo app in Java
      3. Frequently asked questions
      4. Summary
    24. 20. Drawing Graphics
      1. Understanding the Canvas class
        1. Getting started drawing with Bitmap, Canvas, and ImageView
          1. Canvas and Bitmap
          2. Paint
          3. ImageView and Activity
          4. Canvas, Bitmap, Paint, and ImageView – quick summary
      2. Using the Canvas class
        1. Preparing the instances of the required classes
        2. Initializing the objects
        3. Setting the Activity content
      3. The Canvas Demo app
        1. Creating a new project
          1. Coding the Canvas demo app
            1. Exploring the Bitmap initialization
          2. Drawing on the screen
            1. Explaining Color.argb
      4. Android coordinate system
        1. Plotting and drawing
      5. Creating Bitmaps
      6. Manipulating Bitmaps
        1. What is a Bitmap exactly?
        2. The Matrix class
          1. Inverting a bitmap to face the opposite direction
          2. Rotating the bitmap to face up and down
      7. Bitmap manipulation demo app
        1. Add the graphic to the project
      8. Frequently asked question
      9. Summary
    25. 21. Threads, and Starting the Live Drawing App
      1. Creating the Live Drawing project
      2. Looking ahead at the Live Drawing app
      3. Coding the LiveDrawingActivity class
      4. Coding the LiveDrawingView class
      5. Coding the LiveDrawingView class
        1. Adding the member variables
        2. Coding the LiveDrawingView constructor
        3. Coding the draw method
          1. Adding the printDebuggingText method
        4. Understanding the draw method and the SurfaceView class
      6. The game loop
      7. Threads
        1. Problems with threads
      8. Implementing the game loop with a thread
        1. Implementing Runnable and providing the run method
        2. Coding the thread
        3. Starting and stopping the thread
        4. Using the Activity lifecycle to start and stop the thread
        5. Coding the run method
      9. Running the app
      10. Summary
    26. 22. Particle Systems and Handling Screen Touches
      1. Adding custom buttons to the screen
      2. Implementing a particle system effect
        1. Coding the Particle class
        2. Coding the ParticleSystem class
        3. Spawning particle systems in the LiveDrawingView class
      3. Handling touches
        1. Coding the onTouchEvent method
        2. Finishing the HUD
      4. Running the app
      5. Summary
    27. 23. Supporting Different Versions of Android, Sound Effects, and the Spinner Widget
      1. Handling different versions of Android
        1. Detecting the current Android version
      2. The Soundpool class
        1. Initializing SoundPool the new way
          1. Initializing SoundPool the old way
          2. Loading sound files into memory
          3. Playing a sound
          4. Stopping a sound
      3. Sound demo app introducing Spinner widget
        1. Making sound FX
        2. Laying out the sound demo
        3. Coding the Sound demo
      4. Summary
    28. 24. Design Patterns, Multiple Layouts, and Fragments
      1. Introducing the model-view-controller pattern
        1. Model
        2. View
        3. Controller
      2. Android design guidelines
      3. Real-world apps
      4. Device detection mini-app
        1. Coding the MainActivity class
          1. Unlocking the screen orientation
        2. Running the app
      5. Configuration qualifiers
        1. The limitation of configuration qualifiers
      6. Fragments
        1. Fragments have a lifecycle too
          1. onCreate
          2. onCreateView
          3. onAttach and onDetach
          4. onStart, onPause, and onStop
        2. Managing Fragments with FragmentManager
      7. Our first Fragment app
      8. Fragment reality check
      9. Frequently asked question
      10. Summary
    29. 25. Advanced UI with Paging and Swiping
      1. Angry birds classic swipe menu
      2. Building an image gallery/slider app
        1. Implementing the layout
        2. Coding the PagerAdapter class
        3. Coding the MainActivity class
        4. Running the gallery app
      3. Building a Fragment Pager/slider app
        1. Coding the SimpleFragment class
        2. The fragment_layout
        3. Coding the MainActivity class
        4. The activity_main layout
        5. Running the fragment slider app
      4. Summary
    30. 26. Advanced UI with Navigation Drawer and Fragment
      1. Introducing the NavigationView
      2. Examining the Simple Database app
        1. Insert
        2. Delete
        3. Search
        4. Results
      3. Starting the Simple Database project
      4. Exploring the auto-generated code and assets
      5. Coding the Fragment classes and their layouts
        1. Creating the empty files for the classes and layouts
        2. Coding the classes
        3. Designing the layouts
        4. Designing content_insert.xml
        5. Designing content_delete.xml
        6. Designing content_search.xml
        7. Designing content_results.xml
      6. Using the Fragment classes and their layouts
        1. Editing the Navigation Drawer menu
        2. Adding a holder to the main layout
        3. Coding the MainActivity.java
      7. Summary
    31. 27. Android Databases
      1. Database 101
        1. What is a database
        2. What is SQL
        3. What is SQLite
      2. SQL syntax primer
        1. SQLite example code
          1. Creating a table
          2. Inserting data into the database
          3. Retrieving data from the database
          4. Updating the database structure
      3. Android SQLite API
        1. SQLiteOpenHelper and SQLiteDatabase
        2. Building and executing queries
        3. Database cursors
      4. Coding the database class
      5. Coding the Fragment classes to use the DataManager
      6. Running the Age Database app
      7. Summary
    32. 28. Coding a Snake Game Using Everything We Have Learned So Far
      1. How to play
      2. Getting started with the Snake game
        1. Make the app full screen and landscape
        2. Adding some empty classes
        3. Coding SnakeActivity
        4. Adding the sound effects
      3. Coding the game engine
        1. Coding the members
        2. Coding the constructor
        3. Coding the newGame method
        4. Coding the run method
        5. Coding the updateRequired method
        6. Coding the update method
        7. Coding the draw method
        8. Coding onTouchEvent
        9. Coding pause and resume
      4. Running the game
      5. Adding the graphics
      6. Coding the apple
        1. The Apple constructor
      7. Using the apple
        1. Running the game
      8. Summary
    33. 29. Enumerations and Finishing the Snake Game
      1. Enumerations
      2. Add the sound to the project
      3. Coding the Snake class
        1. Coding the constructor
        2. Coding the reset method
        3. Coding the move method
        4. Coding the detectDeath method
        5. Coding the checkDinner method
        6. Coding the draw method
        7. Coding the switchHeading method
        8. Using the snake class and finishing the game
      4. Running the completed game
      5. Summary
    34. 30. A Quick Chat Before You Go
      1. Publishing
      2. Making an app!
      3. Carrying on learning
        1. Carrying on reading
        2. GitHub
        3. StackOverflow
        4. Android user forums
        5. Higher-level study
      4. My other channels
      5. Goodbye and thank you
    35. Other Books You May Enjoy
      1. Leave a review - let other readers know what you think
    36. Index