C. Java for Android Developers

This appendix contains examples of a number of Java techniques frequently used in Android applications and by seasoned Java developers but not always found in beginner Java books and tutorials. If you are new to Java, this information, used in conjunction with a good Java reference, can help you develop Android applications quickly and effectively.

Learning the Java Programming Language

Android applications are written in Java, so learn Java first—it’s essential. This appendix does not teach you standard Java syntax or object-oriented programming and how the object hierarchy works. For that, you should get good reference materials such as books or websites that work for you and, if necessary, take some classes. (It should go without saying that learning programming fundamentals comes first, but experience has shown us that many people try to write Android apps without doing so. Learning programming language syntax, such as Java, is not the same as learning how to program.) Without basic Java skills, you’re going to have trouble developing good Android applications. It’s like asking someone to write a poem in a foreign language without first learning how to speak the language . . . or learning what a poem is.

We, the authors, believe that the Android platform is a good way to learn Java development. This works only if you are either under the instruction of a teacher who is guiding you through programming and application development topics simultaneously, or you are a real self-starter who looks up things as you go and pulls together information from a variety of sources outside this book.


Image Tip

A great resource for learning Java is the online documentation found here: http://docs.oracle.com/javase/tutorial/tutorialLearningPaths.html.


Learning the Java Development Tools

Once you’ve begun learning the basics of Java programming, you’ve got to learn to use the tools associated with development. Many Android developers use the free Android IDE (a version of the Eclipse IDE) included with the Android Developer Tools (ADT) Bundle for Android development. Others use their own copy of the Eclipse IDE with the ADT Plugin. Android Studio, based on ItelliJ IDEA, has been released as another development environment for Android.

This book uses the Android IDE from the ADT Bundle in its examples. Get familiar with the tool so that you can easily debug your applications, or at least read the errors generated by them. We frequently receive emails from frustrated beginners who have no idea why their applications are not compiling but would have been able to figure it out themselves if only they had looked at the errors generated by the Android IDE, for simple mistakes like missing semicolons, mismatched brackets, or undefined variables. The Android IDE spits out errors on the Problems tab at the bottom of the screen.

Familiarizing Yourself with Java Documentation

Javadocs are automatically generated Java class documentation files created from the source code. All the Java references associated with the Android SDK are available for download through the Android SDK Manager and online at http://d.android.com/reference/ (the Reference tab on the website). This book refers to various Android SDK classes and interfaces, but if we were to reproduce the class documentation for the entire Android SDK, the book would need to be many, many volumes.

Understand that this book, and any other book on Android development for that matter, must be used along with the full class documentation. Android developers must constantly refer to the class documentation to choose the right methods and supply the correct parameters. Do not make the mistake of thinking you can develop applications without this core documentation. You’ll become familiar with the most commonly used class documentation as you get up to speed, but with new classes and methods being added all the time, it’s not practical to even attempt to memorize all of it.

Understanding Java Shorthand

Now let’s talk about some of the less common Java syntax you frequently see used in Android applications for one reason or another. These are techniques and shorthand that are often seen in the field but rarely covered in your typical Java class or beginner’s reference, yet you find them in the simplest of examples on the Android Developers website, in our books, and in other references.

Java shorthand is rarely shown in books, which tend to want to spell out each individual coding step, often on its own line, for readability. Some Java professionals prefer that style, whereas others strive to make the perfect, terse line of code that does everything, often at the expense of readability. Here are some examples of Java shorthand you’re likely to see in Android applications.

Chaining Methods and Unnecessary Temp Variables

Java developers often want to avoid creating unnecessary variables, especially temp variables that are used once to store the result of a calculation, either in the middle of a larger calculation, or for a return value. Therefore, you are likely to see statements evaluated as return values, like this:

int sum(int a, int b)
{
    return (a+b);
}

This is equivalent to a longer method with a temp variable, as in the following:

int sumVerbose(int a, int b)
{
    int temp = a + b;
    return temp;
}

Android developers often take these Java features to the extreme in what is called method chaining. This means that the interim return values of the methods are not stored in their own named variables but are simply used “on the fly.” Here is a typical method chaining example:

InputStream isIconData = getResources().openRawResource(R.drawable.icon);

This is equivalent to the following:

Resources myAppResources = this.getResources();
InputStream isIconData = myAppResources.openRawResource(R.drawable.icon);

Note that the this keyword has also been dropped. You often see method chaining in builder-style classes. For example, with the Android AlertDialog classes, you can either construct a new AlertDialog class and call a bunch of setter methods, or use the AlertDialog.Builder class to chain all of the setter methods together, ending with a call to the builder’s create() method that ultimately returns an AlertDialog (not an AlertDialog.Builder class, which is used only for chaining). Although you don’t have to use method chaining, you should recognize what it is and how to read it, because the Android SDK sample applications (and our books) use this technique frequently.

Looping Infinitely

In Java, you can have empty statements simply by terminating a blank line of code with a semicolon. This trick is often used to specify for loop conditionals to create an infinite loop, like this:

for (;;) {
    // Loop
}

Each of the for loop components is an empty statement. This evaluates to be true and therefore the loop continues indefinitely. As with any code design, make sure any infinite loops you create have reasonable exit cases.

There’s also a for-each syntax you might see with arrays and classes that implement the Iterable interface. To use the for-each loop syntax, you need to define your loop variable, then put a colon, and then specify the name of your array or class. For example:

int aNums[] = { 2, 4, 6 };
for (int num : aNums) {
    String strToPrint = num;
}

This is equivalent to the following:

int aNums[] = { 2, 4, 6 };
for (int i = 0; i < aNums.length; i++) {
    String strToPrint = aNums[i];
}

Note that we’ve also been lazy about the automatic toString() conversion done on the int values when assigned to the String variables.

Working with Unary and Ternary Operators

Java supports unary operations, which allow developers to easily increment or decrement variable values by 1 using ++ and --. For example:

int counter = 1;
counter++;
counter--;

This code is equivalent to the following:

int counter = 1;
counter = counter + 1;
counter = counter - 1;

Unary operators can appear before (prefix) or after (postfix) the variable. The location of the operator dictates whether the operation happens before or after the rest of the expression is evaluated. For example, the following code shows how unary operators work by manipulating a variable called counter using Android logging:

int counter = 0;
Log.i(DEBUG_TAG, "The counter value is =" + counter++);       // prints 0
Log.i(DEBUG_TAG, "The counter value is =" + counter);         // prints 1
Log.i(DEBUG_TAG, "The counter value is =" + counter--);       // prints 1
Log.i(DEBUG_TAG, "The counter value is =" + counter);         // prints 0
Log.i(DEBUG_TAG, "The counter value is =" + (++counter));     // prints 1
Log.i(DEBUG_TAG, "The counter value is =" + --counter);       // prints 0

There are also a number of other operators, such as +=, -=, *=, /=, %=, ^=, >>=, <<=, &=, |=.

Java also supports ternary operators for if-else shorthand. You might see conditional statements followed by a question mark (?), then a statement to evaluate whether the conditional is true, then a colon (:) and another statement to evaluate whether the conditional is false. The result of a ternary operator is the value of the evaluated statement. Here’s an example of a ternary operator in use in a simple conditional evaluation:

int lowNum = 1;
int highNum = 99;
int largerNum = lowNum < highNum ? highNum : lowNum;

This code is equivalent to the following:

int lowNum = 1;
int highNum = 99;
int largerNum;
if(lowNum < highNum) {
    largerNum = highNum;
} else {
    largerNum = lowNum;
}

Working with Inner Classes

You learned (we hope) about the object-oriented programming and class hierarchy in your basic Java instruction, but not all instructors or books talk about inner classes or, perhaps more importantly, anonymous inner classes.

An inner class is a class whose scope and definition are encompassed in another class. Most classes in Java are top-level classes. These classes, and the objects they define, are standalone. You can also create nested classes to encapsulate and define subordinate objects that make sense only in the context of the outer class. Nested classes are called inner classes. Inner classes can have all the features of a regular class, but their scope is limited. Inner classes have another benefit: they have full access to the class in which they are nested. This feature makes inner classes perfect for implementing adapter or builder functionality, as you frequently see them used in Android.

Inner classes exist only to help the developer organize code; the compiler treats inner classes just like any other class, except that the inner classes have a limited scope and are therefore tethered to the class they are defined with.

Here is an example of a top-level class with two inner classes:

public class Car {
    // Car fields, including variables of type Engine and Wheels
    // Misc car methods

    class Engine {
        // Car engine fields
        // Get/Set engine methods
        // Functional engine method (goForward, goReverse, etc.)
        // Can access Car fields/methods
    }

    class Wheels {
        // Car wheel fields
        // Get/Set wheel methods (getTirePressure, etc.)
        // Functional wheel method (turnRight, turnLeft, etc.)
        // Can access Car fields/methods
    }
}

The Car class has two inner classes: Engine and Wheels. Although all user-related data and functionality can be defined in the Car class, using the inner classes to compartmentalize functionality can make code easier to read and maintain. The inner classes Engine and Wheels also have access to the protected/private fields and methods available within the Car class, which they might not otherwise have due to security, if they were defined as standalone classes. Remember that you cannot use or instantiate the Engine or Wheels classes except with an instance of the Car class, but the inner classes can access any fields or methods available in the outer class Car, as needed.


Image Tip

One specific use for inner classes is as static inner classes. A static inner class defines behavior that is not tied to a specific object instance but applies across all instances.


Let’s look at another way inner classes are used. Android developers often use anonymous inner classes to define specialized listeners, which register callbacks for specific behavior when an event occurs, on the fly. For example, to listen for clicks on a Button control, the developer uses the setOnClickListener() method, which takes a single parameter: a View.OnClickListener object. You can define an entirely new MyOnClickListener class, or you can simply define the class inline in code, without naming it at all (thus, the anonymous part). The following code uses the anonymous inner class technique to create, define, and assign a custom View.OnClickListener to a Button control:

Button aButton = (Button) findViewById(R.id.MyButton);
aButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // User clicked my button, do something here!
    }
});

You often see threading done in a similar fashion:

new Thread() {
    public void run() {
        doWorkHere();
    }
}.start();

This code defines a new Thread class, implements the run() method, and starts the thread, all in one “line” of code.

Summary

To program Android applications, a basic understanding of object-oriented programming and Java is essential, in addition to being able to utilize the ADT. Java is an evolving language. Some older reference books do not cover the latest the language has to offer, and different developers have different coding styles. We have tried to make our examples easy to read, even if that means they are a bit verbose.

Quiz Questions

1. True or false: Method stacking means interim method return values are not stored in their own named variables but are simply used “on the fly.”

2. What is the syntax for creating an infinite for loop in Java?

3. What is the syntax for creating a for-each loop involving an array of strings in Java?

4. Provide an example line of code that uses the += unary operator.

5. Provide an example line of code that uses the ternary operator in a Boolean evaluation that returns a Boolean true or false value.

Exercises

1. Read the official Java documentation for learning the Java language found here:

http://docs.oracle.com/javase/tutorial/java/index.html.

2. Read the official Java documentation for learning the essential Java classes found here:

http://docs.oracle.com/javase/tutorial/essential/index.html.

3. Read the official Java documentation for learning Java collections found here:

http://docs.oracle.com/javase/tutorial/collections/index.html.

4. Read the official Java documentation for learning Java generics found here:

http://docs.oracle.com/javase/tutorial/extra/generics/index.html.

References and More Information

Oracle Java Tutorials: “Java Tutorials Learning Paths”:

http://docs.oracle.com/javase/tutorial/tutorialLearningPaths.html

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.18.33