Java Programming for Android Developers For Dummies book cover

Java Programming for Android Developers For Dummies

Author:
Published: November 7, 2016

Overview

Develop the next killer Android App using Java programming!

Android is everywhere! It runs more than half the smartphones in the U.S.—and Java makes it go. If you want to cash in on its popularity by learning to build Android apps with Java, all the easy-to-follow guidance you need to get started is at your fingertips. Inside, you'll learn the basics of Java and grasp how it works with Android; then, you'll go on to create your first real, working application. How cool is that?

The demand for Android apps isn't showing any signs of slowing, but if you're a mobile developer who wants to get in on the action, it's vital that you get the necessary Java background to be a success. With the help of Java Programming for Android Developers For Dummies, you'll quickly and painlessly discover the ins and outs of using Java to create groundbreaking Android apps—no prior knowledge or experience required!

  • Get the know-how to create an Android program from the ground up
  • Make sense of basic Java development concepts and techniques
  • Develop the skills to handle programming challenges
  • Find out how to debug your app

Don't sit back and watch other developers release apps that bring in the bucks! Everything you need to create that next killer Android app is just a page away!

Develop the next killer Android App using Java programming!

Android is everywhere! It runs more than half the smartphones in the U.S.—and Java makes it go. If you want to cash in on its popularity by learning to build Android apps with Java, all the easy-to-follow guidance you need to get started is at your fingertips. Inside, you'll learn the basics of Java and grasp how it works with Android; then, you'll go on to create your first real, working application. How cool is that?

The demand for Android apps isn't showing any signs of slowing, but if you're a mobile developer who wants to get in on the action, it's vital that you get the necessary Java background

to be a success. With the help of Java Programming for Android Developers For Dummies, you'll quickly and painlessly discover the ins and outs of using Java to create groundbreaking Android apps—no prior knowledge or experience required!
  • Get the know-how to create an Android program from the ground up
  • Make sense of basic Java development concepts and techniques
  • Develop the skills to handle programming challenges
  • Find out how to debug your app

Don't sit back and watch other developers release apps that bring in the bucks! Everything you need to create that next killer Android app is just a page away!

Java Programming for Android Developers For Dummies Cheat Sheet

Android is the open source, Linux- and Java-based, software framework for mobile and portable devices. The Android operating system powers 86% of all smartphones in the world today. Android not only has a majority of users, but with the help of a (very well designed) Java-based software development kit (SDK, for short), developing apps can be straightforward and fun. This cheat sheet concentrates on commonly used code handy for any developer wishing to try their hand at building their own Android applications with the help of Java.

Articles From The Book

27 results

Java Articles

Programming with Java: Keeping Things Simple in Your Android App

The key to succeeding with Java programming is to keep it simple. Most programs operate entirely in the virtual realm. They have no bricks, nails, or girders. You can type a fairly complicated program in minutes. Even with no muscle and no heavy equipment, you can create a structure whose complexity rivals that of many complicated physical structures. You, the developer, have the power to build intricate, virtual bridges. One goal of programming is to manage complexity. A good app isn't simply useful or visually appealing — a good app's code is nicely organized, easy to understand, and easy to modify. Certain programming languages, like C++, support multiple inheritance, in which a class can have more than one parent class. For example, in C++ you can create a Book class, a TeachingMaterial class, and a Textbook class. You can make Textbook extend both Book and TeachingMaterial. This feature makes class hierarchies quite flexible, but it also makes those same hierarchies extremely complicated. You need tricky rules to decide how to inherit the move methods of both the computer's Mouse class and the rodent's Mouse class. To avoid all this complexity, Java doesn't support multiple inheritance. In Java, each class has one (and only one) superclass. A class can have any number of subclasses. You can (and will) create many subclasses of Android's AppCompatActivity class. And other developers create their own subclasses of Android's AppCompatActivity class. But classes don't have multiple personalities. A Java class can have only one parent. The Executive class cannot extend both the FullTimeEmployee class and the PartTimeEmployee class.

The relationship between a class and its subclass is one of inheritance. In many real-life families, a child inherits assets from a parent. That's the way it works.

But consider the relationship between an editor and an author. The editor says, “By signing this contract, you agree to submit a completed manuscript by the fifteenth of August.” Despite any excuses that the author gives before the deadline date, the relationship between the editor and the author is one of obligation. The author agrees to take on certain responsibilities; and, in order to continue being an author, the author must fulfill those responsibilities. (By the way, there's no subtext in this paragraph — none at all.) Now consider Barry Burd. Who? Barry Burd — that guy who writes Java Programming for Android Developers For Dummies, 2nd Edition, and certain other For Dummies books (all from Wiley Publishing). He's a college professor, and he's also an author. You want to mirror this situation in a Java program, but Java doesn't support multiple inheritance. You can't make Barry extend both a Professor class and an Author class at the same time. Fortunately for Barry, Java has interfaces. A class can extend only one parent class, but a class can implement many interfaces. A parent class is a bunch of stuff that a class inherits. On the other hand, as with the relationship between an editor and an author, an interface is a bunch of stuff that a class is obliged to provide. Here's another example. Though a company might hire consultants, consultants who work for the company aren't employees. Consultants are normally self-employed. They show up temporarily to help companies solve problems and then leave the companies to work elsewhere. In the United States, differentiating between an employee and a consultant is important: So serious are the U.S. tax withholding laws that labeling a consultant an “employee” of any kind would subject the company to considerable legal risk. To include consultants with employees in your code, you need a Consultant class that’s separate from your existing Employee class hierarchy. On the other hand, consultants have a lot in common with a company's regular employees. For example, every consultant has a getPayString method. You want to represent this commonality in your code, so you create an interface. The interface obligates a class to give meaning to the method name getPayString. package com.allyourcode.company; public interface Payable { public String getPayString(); } The element in the code above isn't a class — it's a Java interface. Here’s what the listing's code says: As an interface, the getPayString method has a header, but no body. In this interface, the getPayString method takes no arguments and returns a value of type String. A class that claims to implement the Payable interface must provide (either directly or indirectly) a body for the getPayString method. That is, a class that claims to implement Payable must, in one way or another, implement the getPayString method. The next two sections of code implement the Payable interface and provide bodies for the getPayString method. package com.allyourcode.company; import java.text.NumberFormat; import java.util.Locale; public class Consultant implements Payable { String name; double hourlyFee; int hoursWorked; static NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US); public Consultant() { } public Consultant(String name, double hourlyFee, int hoursWorked) { this.name = name; this.hourlyFee = hourlyFee; this.hoursWorked = hoursWorked; } public double pay() { return hourlyFee * hoursWorked; } @Override public String getPayString() { return name + ", " + currency.format(pay()) + "\n"; } } Check out this code: Another Class Implements the Interface package com.allyourcode.company; public class Employee implements Payable { String name; String jobTitle; int vacationDays; double taxWithheld; public Employee() { } public Employee(String name, String jobTitle) { this.name = name; this.jobTitle = jobTitle; } @Override public String getPayString() { return name + ", Pay not known\n"; } } Both the Consultant and Employee classes implement the Payable interface — the interface that summarizes what it means to be paid by the company. With this in mind, consider this code: package com.allyourcode.a10_10; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.allyourcode.company.Consultant; import com.allyourcode.company.Employee; import com.allyourcode.company.Payable; public class MainActivity extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView); Employee employee = new Employee("Barry", "Author"); Consultant consultant = new Consultant("Willy", 100.00, 30); textView.setText(""); displayPay(employee); displayPay(consultant); } void displayPay(Payable payable) { textView.append(payable.getPayString()); } } The displayPay method doesn't know anything about Employee classes or Consultant classes. All the displayPay method knows is that it wants its parameter to implement the Payable interface. As long as the object you pass to displayPay implements the Payable interface, the displayPay method's body can safely call the getPayString method. Both the Employee and Consultant classes implement the Payable interface. So, you can pass an Employee object to the displayPay method, and pass a Consultant object to the displayPay method. That flexibility — the ability to pass more than one kind of object to a method — illustrates the power of Java's interfaces. Two otherwise unrelated classes (Employee and Consultant) both implement the Payable interface.

The dotted line isn't part of standard UML. The folks who manage the standard have much better ways to represent interfaces.

Java Articles

Programming with Java: Some Observations about Android's Classes

When you start a new Java project, Android Studio offers to create an activity for your project. Android Studio offers you several different kinds of activities, such as a Basic Activity, an Empty Activity, a Login Activity, and so on. If you ask for an Empty Activity, you get this code: package com.allyourcode.a10_11; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } The code declares a class named MainActivity. This name MainActivity isn't part of the Android API library. It's a name that you make up when you create a new Android project. (Actually, Android Studio makes up the name. You accept the name or change it to some other name when you follow the steps to create a new project.) The MainActivity class extends a class that belongs to Android's SDK library, namely, the AppCompatActivity class. In other words, the MainActivity object is an AppCompatActivity object. The MainActivity object has all the rights and responsibilities that any AppCompatActivity instance has. For example, the MainActivity has an onCreate method, which it override. In fact, the MainActivity class inherits about 460 lines of code from Android's AppCompatActivity class, which inherits about 1,000 lines from Android's FragmentActivity class, which inherits about 6,700 lines from Android's Activity class. The inherited methods include ones such as getCallingActivity, getCallingPackage, getParent, getTitle, getTitleColor, getWindow, onBackPressed, onKeyDown, onKeyLongPress, onLowMemory, onMenuItemSelected, setTitle, setTitleColor, startActivity, finish, and many, many others. You inherit all this functionality with two simple words: extends AppCompatActivity.

In the terminology of familial relationships, your MainActivity class is a descendant of Android's Activity class. Your MainActivity class is a kind of Activity.

This image, taken directly from Android's online documentation, summarizes this information about the AppCompatActivity class.

Bookmark the page for easy access to Android's API library documentation.

In addition to being a subclass, the AppCompatActivity class implements a bunch of interfaces, including the AppCompatCallback interface, the TaskStackBuilder interface, and others. You don't have to remember any of this. If you ever need to know it, you can look it up on Android's documentation page.

Java's super keyword, revisited

The word super stands for the superclass's constructor. Different code used the super keyword in a different ways. Yes, super always has something to do with a class's parent class. But, no, super doesn't always refer to the parent class's constructor. In an onCreate method, the call super.onCreate(savedInstanceState) sends savedInstanceState to the parent class's onCreate method. The parent class is the AppCompatActivity class. So Java calls the AppCompatActivity class's onCreate method. The AppCompatActivityclass's onCreate method contains its own call to super.onCreate(savedInstanceState). The AppCompatActivity class's parent is the FragmentActivity class. So Java passes savedInstanceState to the FragmentActivity class's onCreate method. And so on. It's not until you get to the Activity class — your MainActivity class's great-grandparent — that the code makes direct use of the savedInstanceState variable. From this savedInstanceState information, the code puts the activity back the way it was before the system destroyed it.

Casting, again

When you call findViewById, Java doesn't know what kind of view it will find. The findViewById method always returns a View instance, but lots of Android's classes extend the View class. For example, the classes Button, TextView, ImageView, CheckBox, Chronometer, and RatingBar all extend Android's View class. If you type the following code: <strong>// DON'T DO THIS!!</strong> TextView textView; textView = findViewById(R.id.textView); Java lets out a resounding, resentful roar: “How dare you assume that the object returned by a call to findViewById refers to an instance of the TextView class!” (Actually, Java quietly and mechanically displays an Incompatible types error message in Android Studio's editor.) Narrowing means trying to assign a long value to an int value. A long value has 64 bits, and an int value has only 32 bits. So the attempt at narrowing fails. In the code you find here, the bad findViewById call is another attempt to do narrowing — assigning the View value returned by a method call to a TextView variable. The TextView class is a subclass of the View class, so the assignment fails miserably. appease the Java gods by adding a casting operator to the code. You tell Java to convert whatever pops out of the findViewById method call into a TextView object. textView = <strong>(TextView)</strong> findViewById(R.id.textView1); While you're typing the code, Java humors you and says, “Your casting operator shows me that you're aware of the difference between a TextView and any old View. I’ll do my best to interpret the View object that I find at runtime as a TextView object.” (Actually, while you're typing the code, Java says nothing. The fact that Java doesn't display any error messages when you use this casting trick is a good sign. Java's casting feature saves the day!)

Casting prevents you from seeing an error message while you develop your code. In that way, casting is quite a useful feature of Java. But casting can't save you if your code contains runtime errors. When you type

textView = (TextView) findViewById(R.id.textView1); you verify that the name textView represents a TextView widget. When the app runs, Java grabs the R.id.textView widget from the activity_main.xml file, and everything works just fine. But you may sometimes forget to check your R.java names against the components in the XML file. A call to findViewById surprisingly spits out a Button component when your casting tells Java to expect a TextView widget. When this happens, Java chokes on the casting operator and your app crashes during its run. Back to the drawing board!

Java Articles

Using Java’s Lambda Expressions in Your Android App

Sometimes, if you open code in Android Studio's editor and hover the mouse over certain words, you get an interesting surprise. Android Studio tells you that you can replace the anonymous inner class with a lambda expression. Okay. What's a lambda expression? For starters, lambda is a letter in the Greek alphabet, and the term lambda expression comes from papers written in the 1930s by mathematician Alonzo Church. In 2013, Oracle released Java 8, adding lambda expressions to the Java language. And in 2016, Google made Java 8 features available to Android developers. What is a lambda expression exactly? A lambda expression is a concise way of declaring an interface that contains only one method. For example, an anonymous OnClickListener could have only one method, namely, the onClick method. So you can replace this anonymous OnClickListener with a lambda expression. If you respond to the message by pressing Alt+Enter, Android Studio offers you a Replace with Lambda option. If you accept this option, Android Studio turns your code into this stuff. package com.allmycode.a11_05; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button button; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(<strong>view -> textView.setText(R.string.you_clicked)</strong>); textView = (TextView) findViewById(R.id.textView); } } This code uses a lambda expression. The image illustrates the transition from a class that implements a one-method interface to a lambda expression. Notice the lightweight role of the word view. When you declare an onClick method, you give the method a parameter of type View even if the statements inside the method don't use that parameter. In the same way, when you create a lambda expression for an onClick method, you preface the -> symbol with a parameter name, even if you don't use that parameter name to the left of the -> symbol.

In order to use lambda expressions, you must satisfy certain requirements. For example, you must compile your code with Java 8 or higher. Your Android Studio version must be 2.1 or higher. And your project's build.gradle file must include the following code:

android { ... defaultConfig { ... <strong> jackOptions {</strong> <strong> enabled true</strong> <strong> }</strong> } ... }

A lambda expression may have more than one parameter to the left of the -> symbol. If it does, you must enclose all the parameters in parentheses and separate the parameters from one another with commas. For example, the expression

(price1, price2) -> price1 + price2 is a valid lambda expression. If you're comfortable with lambda expressions, you can make your code much more readable. What started out as about ten lines of code can easily become only part of a line.