You are on page 1of 44

1: Learn Java for Android Development: Introduction to Java

In this tutorial series, you’ll become familiar with Java, the programming language used to develop Android
applications. Our goal is to prepare those already familiar with one programming language, such as PHP or
Objective-C, to become comfortable working with the Java programming language and dive into Android app
development. In this tutorial, you’ll get a brief introduction to Java fundamentals, including object oriented
programming, inheritance and more. If you’re new to Java, or just looking to brush up on the details, then this is
the tutorial series for you!

Getting Started
As far as prerequisites go, we’re going to assume you understand how to program (perhaps in PHP, or Visual Basic
or C++), but that you are unfamiliar with the specifics of programming in the Java language. We aren’t going to
teach you to program; we’re going to provide you with clear examples of commonly used Java language constructs
and principles, while pointing out some Android-specific tips and tricks.
What You’ll Need
Technically, you don’t need any tools to complete this tutorial but you will certainly need them to develop Android
applications.
To develop Android applications (or any Java applications, for that matter), you need a development environment
to write and build applications. Eclipse is a very popular development environment (IDE) for Java and the
preferred IDE for Android development. It’s freely available for Windows, Mac, and Linux operating systems.
What is Java?
Android applications are developed using the Java language. As of now, that’s really your only option for native
applications. Java is a very popular programming language developed by Sun Microsystems (now owned by
Oracle). Developed long after C and C++, Java incorporates many of the powerful features of those powerful
languages while addressing some of their drawbacks. Still, programming languages are only as powerful as their
libraries. These libraries exist to help developers build applications.
Some of the Java’s important core features are:
• It’s easy to learn and understand
• It’s designed to be platform-independent and secure, using
virtual machines
• It’s object-oriented
Android relies heavily on these Java fundamentals. The Android SDK includes many standard Java libraries (data
structure libraries, math libraries, graphics libraries, networking libraries and everything else you could want) as
well as special Android libraries that will help you develop awesome Android applications.
Why is Java Easy to Learn?
Java is easy to learn for a variety of reasons. There’s certainly no shortage of Java resources out there to help you
learn the language, including websites, tutorials, books, and classes. Java is one of the most widely discussed,
taught, and used programming languages on the planet. It’s used for many different types of programming projects,
no matter their scale, from web applications to desktop applications to mobile applications.
If you’re coming from a traditional programming background like C or C++, you’ll find Java syntax quite similar.
If you’re not, then take comfort in knowing that you’ve chosen one of the easiest languages to learn. You’ll be up
and running in no time at all.
Finally, Java is one of the most human-readable languages out there, by which we mean that a person who knows
nothing about programming can often look at some Java code and have at least an inkling what it’s doing. Consider
the following example:
char character = 'a';
if(character=='a')
{
doSomething();
} else {
doSomethingElse();
}
the code aloud, you can pretty much tell that this snippet of code is doing. There’s a single letter variable called
character. If the character variable equals the letter a, then we do something (call the doSomething() method),
otherwise we do something else (by calling the doSomethingElse() method).
Why is Platform Independence Important?
With many programming languages, you need to use a compiler to reduce your code down into machine language
that the device can understand. While this is well and good, different devices use different machine languages. This
means that you might need to compile your applications for each different device or machine language—in other
words, your code isn’t very portable. This is not the case with Java. The Java compilers convert your code from
human readable Java source files to something called “bytecode” in the Java world. These are interpreted by a Java
Virtual Machine, which operates much like a physical CPU might operate on machine code, to actually execute the
compiled code. Although it might seem like this is inefficient, much effort has been put into making this process
very fast and efficient. These efforts have paid off in that Java performance in generally second only to C/C++ in
common language performance comparisons.
Android applications run in a special virtual machine called the Dalvik VM. While the details of this VM are
unimportant to the average developer, it can be helpful to think of the Dalvik VM as a bubble in which your
Android application runs, allowing you to not have to worry about whether the device is a Motorola Droid, an HTC
Evo, or the latest toaster running Android. You don’t care so long as the device is Dalvik VM friendly—and that’s
the device manufacturer’s job to implement, not yours.
Why is Java Secure?
Let’s take this bubble idea a bit further. Because Java applications run within the bubble that is a virtual machine,
they are isolated from the underlying device hardware. Therefore, a virtual machine can encapsulate, contain, and
manage code execution in a safe manner compared to languages that operate in machine code directly. The
Android platform takes things a step further. Each Android application runs on the (Linux-based) operating system
using a different user account and in its own instance of the Dalvik VM. Android applications are closely
monitored by the operating system and shut down if they don’t play nice (e.g. use too much processing power,
become unresponsive, waste resources, etc.). Therefore, it’s important to develop applications that are stable and
responsive. Applications can communicate with one another using well-defined protocols.
Compiling Your Code
Like many languages, Java is still a compiled language even though it doesn’t compile all the way down to
machine code. This means you, the developer, need to compile your Android projects and package them up to
deploy onto devices. The Eclipse development environment (used with the Android Development plug-in) makes
this pretty painless. In Eclipse, automatic compilation is often turned on by default. This means that every time you
save a project file, Eclipse recompiles the changes for your application package. You immediately see compile
errors. Eclipse also interprets Java as you type, providing handy code coloring and formatting as well as showing
many types of errors as you go. Often, you can click on the error and have Eclipse automatically fix a typo, or add
an import statement, or provide a method stub for you, saving lots of typing.
You can still manually compile your code if you so desire. Within Eclipse, you’ll find the Build settings under the
project menu. If you have “Build Automatically” turned on, you can still choose the “Clean…” option that will
allow you to do full rebuild of all files. If “Build Automatically” is turned off, “Build All” and “Build Project”
menu options are enabled. “Build All” means to build all of the projects in the workspace. You can have many
projects in an Eclipse workspace.
The build process, for regular Java projects, results in a file with the extension of JAR – Java ARchive. Android
applications take JAR files and package them for deployment on devices as Android PacKage files with an
extension .apk. These formats not only include your compiled Java code, but also any other resources, such as
strings, images, or sound files, that your application requires to run as well as the Application Manifest file,
AndroidManifest.xml. The Android Manifest file is a file required by all Android applications, which you use to
define configuration details about your app.
What is an Object Oriented Programming Language?
Okay. Time for a very brief and 20,000 foot view of object oriented programming (OOP). OOP is a programming
style or technique that relies upon the definition of data structures called objects. For those new to OOP, an object
can be thought of much like a custom data type. For example, you might have a Dog object, which represents the
blueprint for a generic dog, with a name, breed, and gender. You could then create different instances of the Dog
object to represent specific dogs. Each Dog object must be created by calling its constructor (a method that has the
same name as the object itself, and may or may not have parameters for setting initial values). For example, the
following Dog objects use a constructor with three parameters (name, breed, gender):
Dog dog1 = new Dog("Lassie", collie, female);
Dog dog2 = new Dog("Fifi", poodle, female);
Dog dog3 = new Dog("Asta", foxterrier, male);
So where is this Dog object defined? Well, here we need to begin defining some of the fundamental building
blocks of the Java programming language. A class provides a definition for an object. Therefore, there is a Dog
class somewhere—either defined by you or in some library somewhere. Generally speaking, a class will be defined
in its own file, with the filename matching the class name (e.g. Dog.java). There are exceptions to this rule, such as
classes defined within other classes (when a class is declared within a class, it is generally defined for use within
the parent class only as a helper class, and referred to as an inner class).
When you want to reference an object from within another class, you need to include an import statement in the top
of your class file, much like you would use a #include statement in a compiled language like C.
A class typically describes the data and behavior of an object. The behavior is defined using class methods. Method
is the common term for a subroutine in an OOP language. Many common object classes are defined in shared class
libraries like software development kits (SDKs), whereas others are defined by you, the developer, for your own
purposes. Software is then built up by using and manipulating object instances in different ways.
Please realize this is a very generalized definition of OOP. There are entire books written on this subject. If you’d
like to know more about OOP, here are a few resources you might want to check out:
• Wikipedia has a nice overview of OOP
• Sun Java Tutorials on Java
• The Java Tutorials at Oracle
Note: We use a lot of different terminology in this tutorial. There are multiple ways to refer to a given concept (e.g.
superclass vs. parent class), which is confusing to those new to object oriented programming. Different developers
use different terms, and so we have tried to mention synonyms where appropriate. Deciding which terms you will
use is a personal choice.
Understanding Inheritance
Here is another important Java concept you’ll run into a lot: inheritance. Simply put, inheritance means that Java
classes (and therefore objects) can be organized into hierarchies with lower, more specific, classes in the hierarchy
inheriting behavior and traits from higher, more generic, classes.
This concept is best illustrated by example. Let’s pretend we are developing a Java application to simulate an
aquarium. This aquarium has some fish in it. Therefore, we might define a class to represent a fish. This class,
called Fish, could include some data fields (also called attributes, or class member variables) to describe a fish
object: species, color and size; as well as some of its behavior in the form of methods (also called subroutines, or
functions in procedural languages), like eat(), sleep(), and makeBabyFish().
A special type of method, called a constructor, is used to create and initialize an object; constructors are named the
same as their class and may include parameters. The following Fish class has two constructors: one for creating a
generic Fish object and another for constructing a specific Fish object with some initial data. You’ll also see that
the Fish class has two eat() methods: one for eating something random, and another for eating another fish, which
would be represented by another instance of the Fish class:
public class Fish {

private String mSpecies;


private String mColor;
private int mSize;

Fish() {
// generic fish
mSpecies = "unknown";
mColor = "unknown";
mSize = 0;
}
Fish(String species, String color, int size) {
mSpecies = species;
mColor = color;
mSize = size;
}
public void eat() {
// eat some algae
};

public void eat(Fish fishToEat) {


// eat another fish!
};

public void sleep() {


// sleep
};

public void makeBabyFish(Fish fishSpouse, int numBabies) {


// Make numBabies worth of baby fish with Fish spouse
};
}
Classes can be organized into hierarchies, where a derived class (or subclass) includes all the features of its parent
class (or superclass), but refines and adds to them to define a more specific object using the extends keyword. This
is called inheritance.
For example, the Fish class might have two subclasses: FreshwaterFish and SaltwaterFish. These subclasses would
have all the features of the Fish class, but could further customize the objects through new attributes and behaviors
or modified behaviors from the parent class Fish. For example, the FreshwaterFish class might include information
about the type of freshwater environment lived in (e.g. river, lake, pond, or puddle). Similarly, the SaltwaterFish
class might customize the makeBabyFish() method such that the fish eats its mate after breeding (as defined in the
super class) by using the override mechanism, like this:
public class SaltwaterFish extends Fish
{
@Override
public void makeBabyFish(Fish fishSpouse, int numBabies) {
// call parent method
super.makeBabyFish(fishSpouse, numBabies);
// eat mate
eat(fishSpouse);
}
}
Organizing Object Behavior with Interfaces
In Java, you can organize object behaviors in what are called interfaces. While a class defines an object, an
interface defines some behavior that can be applied to an object. For example, we could define a Swimmer
interface that provides a set of methods that are common across all objects that can swim, whether they are fish,
otters, or submergible androids. The Swimmer interface might specify four methods: startSwimming(),
stopSwimming(), dive(), and surface().
public interface Swimmer
{
void startSwimming();
void stopSwimming();
void dive();
void surface();
}
A class like Fish could then implement the Swimmer interface (using the implements keyword) and provide
implementations of the swimming behavior:
public class Fish implements Swimmer {
// Provide implementations of the four methods within the Swimmer interface
}
Organizing Classes and Interfaces with Packages
Class hierarchies, such as our fish classes, can then be organized into packages. A package is simply a set of
classes and interfaces, bundled together. Developers use namespaces to uniquely name packages. For example, we
could use com.mamlambo.aquarium or com.ourclient.project.subproject as our package name to keep track
of our fish-related classes.
2: Learn Java for Android Development: Java Syntax
in this tutorial series, you’ll become familiar with Java, the programming language used to develop Android
applications. Our goal is to prepare those already familiar with one programming language, such as PHP or
Objective-C, to become comfortable working with the Java programming language and dive into Android app
development. In this specific tutorial, you’ll learn the basics of Java syntax, including how to create comments,
define variables, craft conditional statements and iterate using loops. If you’re new to Java, or just looking to brush
up on the details, then this is the tutorial series for you!
Getting Started
As far as prerequisites go, we’re not going to make many assumptions about your programming experience. We
are going to assume you understand how to program (perhaps in PHP, or Visual Basic or C++), but that you are
unfamiliar with the specifics of programming in the Java language. We’re not going to go into the details of why
you would want to do a for-loop versus a while-loop, but we will show you, in Java, the syntax of both types of
loops. Said another way, we aren’t going to teach you to program; we’re going to provide you with clear examples
of commonly used Java language constructs and principles, while pointing out some Android-specific tips and
tricks.
What You’ll Need
Technically, you don’t need any tools to complete this tutorial but you will certainly need them to develop Android
applications.
To develop Android applications (or any Java applications, for that matter), you need a development environment
to write and build applications. Eclipse is a very popular development environment (IDE) for Java and the
preferred IDE for Android development. It’s freely available for Windows, Mac, and Linux operating systems.

Now let’s look at some more helpful Java syntax.


Comments
Most programming languages allow for comments and Java is no different. You can encapsulate any number of
lines of text by beginning your comment with /* and ending your comment with */. For example:
/* MULTILINE
COMMENT */
You can also provide comments after code on a single using //. For example:
int x = 7; // First variable called x equals seven
int y = 8; // Second variable called y equals eight
int result = x + y; // The result variable value should equal 15
Java also has a standard type of comments called Javadoc that can be used to not only comment code, but also
easily create code documentation. This topic is rather large on it’s own, but here’s an example of what Javadoc
comments looks like:
/** This method does something interesting
*
* @param someValue processed and returned
* @param option changes the type of processing done to someValue
* @return The result of someValue being processed
*/
public int sampleMethod(int someValue, boolean option) {
//…
}
Variables
A variable is simply a piece of data. Java variables generally fall into two categories:
• Primitive data types, like int, float, double, char, etc.
• Java objects (as defined by a class definition)
Variables are used for different purposes. Sometimes variables are used to store values that can change, or be
modified, over time. For example, a variable called counter might be incremented on occasion. Other variables,
notably class variables that remain the same for all instances of a given class, should be defined using the static
keyword. Other times variables might represent constants—these variables should use the keyword final to show
they do not change over time.
A variable is only valid within its territory, or scope. Variable scope is often controlled by curly braces { }. When a
variable is defined, it is valid within those braces. If you try to access a variable outside of the braces, it will be
undefined. Class member variables in object-oriented languages are often called attributes. They can also be called
fields or properties.
Like other common programming languages, you’ve got your assignment operator, the equals sign:
int i = 5;
You’ve also got your arithmetic operators like +, -, *, /. Remember to use parenthesis to force the order of
operations as necessary:
int result = (a + b) / c;
Finally, you have your typical unary operators, which allow you to modify a single variable with a simple
statement:
iPositive++; // increment by one; equivalent to iPositive = iPositive + 1;
iPositive --; // decrement by one; equivalent to iPositive = iPositive - 1;
Note that the increment (++) and decrement (–) operators can be prefix or postfix, meaning that the increment can
be executed before or after any conditionals are determined, if the item is used in a loop. Generally, we like to stick
to postfix statements, so code is more readable.
Primitive Data Types
Let’s look at some of the primitive data types available in the Java programming language:
• byte
o A byte variable is an 8-bit signed integer between -128 and 127. Often used for arrays.
• short
o A short variable is a 16-bit signed integer between -32,768 and 32,767. Again, often used for arrays.
• int
o An int variable is a 32-bit signed integer between -2,147,483,648 and 2,147,483,647. This is the
most commonly used “number” variable.
• long
o A long variable is a 64-bit signed integer between -9,223,372,036,854,775,808 and
9,223,372,036,854,775,807. Used when the int data type isn’t big enough.
• float
o A float variable is a single precision 32-bit floating point number.
• double
o A double variable is a double-precision 64-bit floating point number. Use this data type for decimal
values.
• boolean
o A boolean variable has only two possible values: true and false. Use this data type for conditional
statements.
• char
o A char variable is a single 16-bit Unicode character.
Primitive types variables can be defined by specifying the datatype, followed by the variable name, then an equals
sign and an initial value. All Java statements end with an semicolon. For example, the following Java statement
defines a variable called iVal, with an initial value of 1:
int iVal = 1;
Like many other languages, you can define a zero-based array of a specific data type. For example, the following
defines an array of three integer values (first four powers of 2):
int[] aiPowersOfTwo;
aiPowersOfTwo = new int[4];
aiPowersOfTwo [0] = 1; // 2^0=1
aiPowersOfTwo [1] = 2; // 2^1=2
aiPowersOfTwo [2] = 4; // 2^2=4
aiPowersOfTwo [3] = 8; // 2^3=8
Commonly Used Java Objects
The Java libraries provide a number of helpful objects for use with common data structures. All objects are derived
from the Object class. There are class counterparts for all primitive data types. For example, the Integer class
encapsulates an int value and provides a number of helpful methods for manipulating integer data values. For
example, the following Java code instantiates a integer variable called iVal, then creates an Integer object using a
constructor that takes an integer, and then uses an handle method available in the Integer class to extract a float
variable equivalent.
int iVal = 1;
Integer integ1= new Integer(iVal);
float f = integ1.floatValue();
Perhaps the most common object you’ll use in Android applications is the String. The String class is used to
encapsulate human-readable text characters, which are often displayed to the screen. If you are modifying or
building strings up from smaller parts, you’ll also want to check out the StringBuffer and StringBuilder classes.
String strHello = new String("Hello World");
For a list of common Java data types, the Android reference includes documentation for the java.lang package. You
can also find the common input/output objects in the java.io package.
For more complex data structures like lists, queues, stacks, dates, and times, appropriate classes are in the java.util
package.
Finally, Android applications rely on a number of helpful classes that define the commonly used application
components, like Activity, Application, Dialog, and Service. These classes can be found in the android.app
package.
Class Permissions and Access
You can control the visibility of a class as well as its variables and methods by specifying an item’s access level.
The access levels are: public, protected and private. Generally speaking, if you want something to be accessible
from outside a class, use public. If a method or variable should only be accessible from the class itself, use private.
Use protected when the class or any of its subclasses need access.
For example, the following SillySensor class definition defines several variables and methods with different access
levels:
• A class variable called sensorData, which is only visible within the class
• A public constructor that can be called outside the class
• A private method called calibrate(), which can only be called from within the class itself
• A protected method called seedCalibration(), which can be called from within the class itself, or by a
subclass
• A public method called getSensorData(), which can be called from anywhere, allowing for “read-only”
access to the sensorData variable
public class SillySensor
{
private int sensorData;

public SillySensor()
{
sensorData=0;
}

private void calibrate(int iSeed)


{
// Do some calibration here
}

protected void seedCalibration(int iSeed)


{
calibrate(iSeed);
}
public int getSensorData()
{
// Check sensor here

return sensorData;
}

}
Conditionals
Java includes conditional statements, which can be used to execute snippets of code if, and only if, certain
conditions are met. Typically, a conditional statement involves two sides. If the two sides are equivalent, the
statement is true, otherwise it is false.
Java has all the typical conditional operators, such as:
• == equal to, as in (a == b)
• != not equal to, as in (x != y)
• > greater than, as in (z > y)
• >= greater than or equal to, as in (q >= z)
• < less than, as in (b < a)
• <= less than or equal to, as in (a <= z)
And when you need to combine multiple conditional statements into a single larger conditional test, you can use
AND (&&) and OR (||):
• ((a==b)&& (a==c)) // true only if A is equal to B and equal to C
• ((a==b) || (a==c)) // true only if A is equal to B or equal to C
Java has bitwise operators (&, |, ^), shifts (>>, <<), and complement (~) operators as well, should you need them.
See the Java documentation for more details.
Now that you know how to craft a conditional statement, you can create conditional code segments. The simplest
form of a conditional code statement is the if() statement:
boolean condition = true;
if(condition==true)
{
// Execute this code only if condition variable is true
}
If you want to provide alternative code to run if the condition is not met, then use the else clause with the if()
statement:
boolean condition = true;
if(condition==true)
{
// Execute this code only if condition variable value is true
} else {
// Execute this code only if condition variable value is false
}
If you want to handle more than two cases, you can use cascading if-else-if-else statements, like this:
if(iVar==0) {
// variable is zero
} else if (iVar > 0) {
// variable is a positive number
} else {
// variable is a negative number
}
Switch Case Statements
When you have a number of different code paths possible that branch from a single variable value, you can use a
switch() statement. With a switch statement, you supply the variable to check for and provide numerous options to
execute for specific cases. You can also supply a default option to execute if none other cases apply. Each case can
be terminated with a break statement. If a break statement is not supplied, the code will continue executing into the
next case statement.
char singleChar = 'z';
switch(singleChar) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
// singleChar is a vowel! Execute this code!
break;
default:
// singleChar is a consonant! Execute this code instead!
break;
}
Loops
When you want to execute code repeatedly, or using recursion (heh, look that one up if you don’t know what we’re
talking about), Java has support for several different kinds of loops.
To loop continuously provided that a statement is true, use a while() loop:
int numItemsToProcess = 3;
while(numItemsToProcess > 0)
{
// process an item
numItemsToProcess--;
}
If you want to evaluate the conditional loop expression AFTER the first iteration, you can use a do-while loop
instead:
do
{
// check for items to process, update numItemsToProcess as required
// process item, updated numItemsToProcess
} while (numItemsToProcess > 0);
Finally, if you want to loop for a specific number of iterations, you can use a for() loop. A for() loop has three
parameters: the initial value, the terminating value, and the incrementing value. For example, to execute a loop 100
times, printing the numbers 1 through 100, you could use the following for() loop:
for(int i = 1; i <=100; i++)
{
// print i
}
Note: You can also use a break statement to get out of a while(), do-while() or for() loop when necessary. You can
also use a continue statement to skip the rest of a current iteration of a loop and move on to the next iteration
(reevaluating the conditional expression, of course).
Passing By Value vs. By Reference
There are no pointers in Java. Ok, ok, go ahead and breathe a sigh of relief. Life is hard enough without pointers
mucking things up, right?
Ok, now it’s time to pay attention again. In Java, method parameters are passed by value. However, when a method
parameter is an object (that is, anything except a primitive type), only a reference to that object is passed into the
method [much like pointers, sorry!]. Therefore, in order to modify the object passed into a given method, you
generally pass in the object reference, and then act upon it, which modifies the underlying data of the object you
passed in. You cannot, however, swap out the object itself… Here’s a quick example:
Here, we have a class called Cat:
public class Cat {
private String mCatName;

Cat(String name) {
mCatName=name;
}

public String getName() {


return mCatName;
};
public void setName(String strName) {
mCatName = strName;
};
}
Now, let’s try to use this class and pass a Cat object into some functions and see what happens:
void messWithCat(Cat kitty) {
kitty = new Cat("Han");
}

void changeKitty(Cat kitty) {


kitty.setName("Wookie");
}

Cat haveKitten()
{
Cat kitten = new Cat("Luke");
return kitten;
}
Finally, let’s call these methods and see how they act upon Cat object instances:
Cat cat1 = new Cat("Jabba");
Cat cat2 = new Cat("Leia");

cat1.getName(); // Returns Jabba


cat2.getName(); // Returns Leia
messWithCat(cat1);
changeKitty(cat2);
Cat cat3 = haveKitten();
cat1.getName(); // Returns Jabba – Note that object remains unchanged!
cat2.getName(); // Returns Wookie
cat3.getName(); // Returns Luke
Wrapping Up
You’ve just completed a crash-course of the Java programming language. While you may not be ready to write
your first Java app, you should be able to work through the simplest of the Android sample application Java classes
and determine what they’re up to, at least in terms of the Java syntax of things. The first class you’re going to want
to look into for Android development is the Activity class. An Android application uses activities to define
different runtime tasks, and therefore you must define an Activity to act as the entry point to your application. Now
that you’ve got a handle on Java syntax, we highly recommend that you work through a beginner Android tutorial.
You’ve only scratched the surface of Java development for Android development. Check out all the other great
tutorials on Mobiletuts+ to dive deeper into Java and Android development. We highly recommend the following
beginning Android tutorials: Introduction to Android Development by Gyuri Grell and Beginning Android: Getting
Started with Fortune Crunch to begin dabbling in Android development. Good luck!
3: Learn Java for Android Development: Checking Object Type with
Instanceof
This quick lesson in our Learn Java for Android Development series shows you how to conditionally check the
type of an object using the instanceof keyword in Java.
Basic Conditionals
We talked about many of the basic Java conditional statements in the Learn Java for Android Development: Java
Syntax tutorial. For example, Java provides all the typical conditional operators one might expect, including those
to check for equality, inequality, greater than, less than, etc.
Here’s some Java code that checks the value of a numeric variable (called iVar) and provides different code paths
depending on whether the value of iVar is zero, negative or positive:
if(iVar==0) {
// variable is zero
} else if (iVar > 0) {
// variable is a positive number
} else {
// variable is a negative number
}
Using instanceof in Conditional Statements
Now let’s look at a specific Java feature you can also use in conditional statements. Because Java is a fully object
oriented language, you can also test if an object is of a specific type (an instance of a specific class) conditionally
using the instanceof keyword. The instanceof keyword is a Boolean operator, used like a regular mathematical
Boolean conditional operator to generate a true or a false result.
Let’s look at a quick example. Let’s assume we have a parent class called Fish, which has two derived subclasses:
SaltwaterFish and FreshwaterFish. We could use the instanceof keyword to test if an object is an instance of a
specific class (or subclass) by name:
SaltwaterFish nemo = new SaltwaterFish();
if(nemo instanceof Fish) {
// we’ve got some sort of Fish
// could be a Fish (parent class), or subclass of some kind, like
// SaltwaterFish, or FreshwaterFish.

if(nemo instanceof SaltwaterFish) {


// Nemo is a Saltwater fish!
}
}
Using instanceof in Android Development
So, when it comes to Android development, when is the instanceof feature useful? Well, for starters, the Android
SDK classes are organized in typical object oriented fashion: hierarchically. For example, the classes such as
Button, TextView, and CheckBox, which represent different types of user interface controls, are all derived from
the same parent class: View. Therefore, if you wanted to create a method that took a View parameter, but had
different behavior depending upon the specific type of control, you could use the instanceof mechanism to check
the incoming parameter and determine exactly what kind of view control had been passed in.
For example, the following method takes a View parameter, allowing you to pass in any type of View, but
specifically singles out TextView controls for special processing:
void checkforTextView(View v)
{
if(v instanceof TextView)
{
// This is a TextView control
} else {
// This is not a TextView control
}
}
In this example, we might continue by making a call to a method that is only valid for a TextView object and not
the generic View object—in which case, we would likely cast the View parameter to a TextView prior to making
such a call. If, however, we wanted to make a call that is available in all View objects, but behaves differently in
TextView objects, there is no need to test for this. Java will handle calling the appropriate version of the method
specific to TextView. This is one of the great features of object-oriented programming: the most appropriate
version of a given method is called.
Conclusion
In this quick lesson you have learned how to use the instanceof Java keyword to check the type of an object at
runtime and provide conditional code paths based on the result. This is a handy Java feature that Android
developers often rely upon, since the Android SDK is organized hierarchically.
This quick lesson shows you how to work with arrays in Java. This lesson is part of an ongoing series of tutorials
for developers learning Java in order to develop Android applications.
4: Learn Java for Android Development: Working with Arrays
This quick lesson shows you how to work with arrays in Java. This lesson is part of an ongoing series of tutorials
for developers learning Java in order to develop Android applications.
What is an Array?
An array is a common data structure used to store an ordered list of items. The array elements are typed. For
example, you could create an array of characters to represent the vowels in the alphabet:
char aVowels[] = {'a','e','i','o','u'};
Much like C or C++, Java arrays are indexed numerically on a 0-based system. This means the first element in the
array (that is, ‘a’) is at index 0, the second (‘e’) is at index 1, and so on.
Java makes working with arrays easier than many other programming languages. The array itself is an object (of
type array), with all the benefits thereof. For example, you can always check the size of an array using its length
property:
int length = aVowels.length;
What Can I Store In An Array?
You can store any object or primitive type in an array. For example, you can store integers in an array:
int aNums[] = { 2, 4, 6 };
Or, you could store non-primitive types like Strings (or any other class) in an array:
String aStooges[] = {"Larry", "Moe", "Curly"};
Sometimes, you may want to store objects of different types in an array. You can always take advantage of
inheritance and use a parent class for the array type. For example, the Object class is the mother of all classes… so
you could store different types in a single array like this:
float one = 1.0f;
Integer two = new Integer(2);
String three = "three";
Object aObjects[] = {one, two, three};
The elements of a Java object array are references (or handles) to objects, not actual instances of objects. An
element value is null until it is assigned a valid instance of an object (that is, the array is initialized automatically
but you are responsible for assigning its values).
Declaring Arrays
There are a number of ways to declare an array in Java. As you’ve seen, you can declare an array and immediately
provide its elements using the C-style squiggly bracket syntax. For example, the following Java code declares an
array of integers of length 3 and initializes the array all in one line:
int aNums[] = { 2, 4, 6 };
You can also declare an array of a specific size and then assign the value of each element individually, like this:
double aPowersOfTwo[] = new double[5];
aPowersOfTwo[0]=Math.pow(2,0);
aPowersOfTwo[1]=Math.pow(2,1);
aPowersOfTwo[2]=Math.pow(2,2);
aPowersOfTwo[3]=Math.pow(2,3);
aPowersOfTwo[4]=Math.pow(2,4);
This is equivalent to creating an array like this:
double aPowersOfTwoExplicit[] = {1.0d, 2.0d, 4.0d, 8.0d, 16.0d};
There are several other ways to create arrays. For example, you can create the array variable and assign it
separately using the new keyword. You can also put the array brackets before the variable name, if you desire (this
is a style issue). For example, the following Java code defines an array of String elements and then assigns them
individually:
String [] aStopLightColors;
aStopLightColors = new String[3];
aStopLightColors[0] = new String("red");
aStopLightColors[1] = new String("yellow");
aStopLightColors[2] = new String("green");
Modifying Array Content
As you have seen, you can assign array values by using the bracket syntax:
You can retrieve array values by index as well. For example, you could access the second element in the array
called aStopLightColors (defined in the previous section) as follows:
String strCurrentLightColor = aStopLightColors[1];
Iterating Arrays
Finally, arrays are often used as an ordered list of objects. Therefore, you may find that you want to iterate through
the array in order, accessing each element methodically.
There are a number of ways to do this in Java. Because you can always check the size of an array
programmatically, you can use any of the typical for or while loop methods you may find familiar. For example,
the following Java code declares a simple integer array of three numbers and uses a simple for-loop to iterate
through the items:
int aNums[] = { 2, 4, 6 };

for (int i = 0; i < aNums.length; i++) {


String strToPrint = "aNums[" + i + "]=" + aNums[i];
}
Java also provides a very handy for-each loop to iterate through arrays in a friendly fashion. The for-each loop
helps avoid silly programming mistakes so common in loops (off-by-one errors, etc.). 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. For
example, the following code provides the similar loop structure as the previous for-loop shown above:
for (int num : aNums) {
String strToPrint = num;
}
As you can see, the for-each loop is slick. However, you no longer know the index while iterating. Thus, it can't be
used in all situations.
Conclusion
In this quick lesson you have learned about arrays in Java. Arrays are a fundamental data structure used for Java
programming that store an ordered number of objects of a given type in an organized fashion. In Java, arrays are
objects themselves and store references to objects, making assignment and use easier (but subtly different) than
how arrays are employed in other programming languages.
In this tutorial, you’ll become familiar with the concept of Java reflection: the ability of a class or object to
examine details about its own implementation programmatically.

5: Learn Java for Android Development: Reflection Basics


In this tutorial, you’ll become familiar with the concept of Java reflection: the ability of a class or object to
examine details about its own implementation programmatically.
Android applications are written in the Java, a programming language that supports reflection—the ability of an
object to examine itself. In this tutorial, you’ll learn the basics of Java reflection, including how to inspect the
methods and fields of a given class, check for the availability of specific methods, and other practical tasks you
may need to use when developing for different versions of the Android SDK.
What You’ll Need
Technically, you don’t need any tools to complete this tutorial but you will certainly need them to develop Android
applications.
To develop Android applications (or any Java applications, for that matter), you need a development environment
to write and build applications. Eclipse is a very popular development environment (IDE) for Java and the
preferred IDE for Android development. It’s freely available for Windows, Mac, and Linux operating systems.
Why Use Reflection?
Reflection gives developers the flexibility to inspect and determine API characteristics at runtime, instead of
compile time. Within the security constraints imposed by Java (e.g. use of public, protected, private), you can then
construct objects, access fields, and invoke methods dynamically. The Java Reflection APIs are available as part of
the java.lang.reflect package, which is included within the Android SDK for developers to use.
So what does this have to do with Android development? Well, with each new version of the Android SDK,
classes, interfaces, methods, etc. are added, updated, and (less frequently) removed. However, Android developers
often want to target devices running different versions of Android with a simple application package. To do this,
Android developers may use reflection techniques to determine, at runtime, if a specific class or method is
available before trying to use it. This allows the developer to leverage new APIs where available while still
supporting the older devices—all in the same application.
Inspecting Classes
Java classes are represented at runtime using the Class (java.lang.Class) class. This class provides the starting point
for all reflection APIs. Within this class, you’ll find many methods for inspecting different aspects of a class, such
as its fields, constructors, methods, permissions, and more. You can also use the Class method called forName() to
load a non-primitive class (e.g. not int, but Integer) by name dynamically at runtime, instead of at compile time:
String sClassName = "android.app.NotificationManager";
try {
Class classToInvestigate = Class.forName(sClassName);

// Dynamically do stuff with this class


// List constructors, fields, methods, etc.

} catch (ClassNotFoundException e) {
// Class not found!
} catch (Exception e) {
// Unknown exception
}
The class (in this case, NotificationManager) need not have the corresponding import statement in your code; you
are not compiling in this class into your application. Instead, the class loader will load the class dynamically at
runtime, if possible. You can then inspect this Class object and use the reflection techniques described in the rest of
this tutorial.
Inspecting the Constructors Available Within a Class
You can inspect the constructors available within a given Class. To get just the constructors that are publicly
available, use getConstructors(). However, if you want to inspect those methods specifically declared within the
class, whether they are public or not, use getDeclaredConstructors() instead. Both methods return an array of
Constructor (java.lang.reflect.Constructor) objects.
For example, the following code iterates through the declared constructors of a class:
Constructor[] aClassConstructors = classToInvestigate.getDeclaredConstructors();
for(Constructor c : aClassConstructors){
// Found a constructor c
}
Once you have a valid Constructor object, you can inspect its parameters and even declare a new instance of the
class using that constructor with the newInstance() method.
Inspecting the Fields Available Within a Class
You can inspect the fields (or attributes) available within a given Class. To get just the methods that are publicly
available, including inherited fields, use getFields(). However, if you want to inspect those fields specifically
declared within the class (and not inherited ones), whether they are public or not, use getDeclaredFields() instead.
Both methods return an array of Field (java.lang.reflect.Field) objects.
For example, the following code iterates through the declared fields of a class:
Field[] aClassFields = classToInvestigate.getDeclaredFields();
for(Field f : aClassFields){
// Found a field f
}
You can also check for a specific public field by name using the getField() method. For example, to check for the
EXTRA_CHANGED_PACKAGE_LIST field of the Intent class (which was added in API Level 8, or Android
2.2), you could use:
String sClassName = "android.content.Intent";
try {
Class classToInvestigate = Class.forName(sClassName);
String strNewFieldName = "EXTRA_CHANGED_PACKAGE_LIST";
Field newIn22 = classToInvestigate.getField(strNewFieldName);

} catch (ClassNotFoundException e) {
// Class not found
} catch (NoSuchFieldException e) {
// Field does not exist, likely we are on Android 2.1 or older
// provide alternative functionality to support older devices
} catch (SecurityException e) {
// Access denied!
} catch (Exception e) {
// Unknown exception }
Once you have a valid Field object, you can get its name using the toGenericString() method. If you have the
appropriate permissions, you can also access the value of that class field using the appropriate get() and set()
methods.
Inspecting the Methods Available Within a Class
You can inspect the methods available within a given Class. To get just the methods that are publicly available,
including inherited methods, use getMethods(). However, if you want to inspect those methods specifically
declared within the class (without inherited ones), whether they are public or not, use getDeclaredMethods()
instead. Both methods return an array of Method (java.lang.reflect.Method) objects.
For example, the following code iterates through the declared methods of a class:
Method[] aClassMethods = classToInvestigate.getDeclaredMethods();
for(Method m : aClassMethods)
{
// Found a method m
}
Once you have a valid Method object, you can get its name using the toGenericString() method. You can also
examine the parameters used by the method and the exceptions it can throw. Finally, if you have the appropriate
permissions, you can also call the method using the invoke() method.
Inspecting Inner Classes
You can inspect the inner classes defined within a Class using getDeclaredClasses() method. This method will
return an array of Class (java.lang.class) objects declared within the parent class. These classes can then be
inspected like any other.
Inspecting Member Modifiers
You can also inspect the flags and security settings—called modifiers—associated with a given Class, Field, or
Method using the getModifiers() method. Interesting modifiers include whether the component is public, private,
protected, abstract, final, or static (amongst others).
For example, the following code checks the security modifiers of a class:
int permissions = classToInvestigate.getModifiers();

if(Modifier.isPublic(permissions)) {
// Class is Public
}
if(Modifier.isProtected(permissions)) {
// Class is Protected
}
if(Modifier.isPrivate(permissions)) {
// Class is Private
}
Keep in mind that you cannot dynamically access or invoke any class, method, or field using reflection that you
would not normally be able to access at compile-time. In other words, regular class security is still applied at
runtime.
Inspecting Class Metadata
You can also inspect the metadata—called annotations—associated with a given class, field or method using the
getAnnotations() method. Interesting metadata associated with a class might include information about
deprecation, warnings, and overrides, among other things.
For example, the following code checks the metadata available for the AbsoluteLayout class. Since this class was
deprecated in Android 1.5, one of the annotations returned is @java.lang.Deprecated() when this code is run on
Android 2.2:
String sClassName = "android.widget.AbsoluteLayout";
try {
Class classToInvestigate = Class.forName(sClassName);

Annotation[] aAnnotations = classToInvestigate.getDeclaredAnnotations();


for(Annotation a : aAnnotations)
{
// Found an annotation, use a.toString() to print it out
}

} catch (ClassNotFoundException e) {
// Class not found!
} catch (Exception e) {
// Handle unknown exception!
}
Similarly, you could simply check for the existence of a specific annotation, such as deprecation, by its type:
if(classToInvestigate.isAnnotationPresent(java.lang.Deprecated.class) == true)
{
// Class is deprecated!
}
Reflection: Handy for Debugging
You can also use reflection to assist with debugging. For example, you might want to use the class keyword to
access the underlying class data for a given type:
import android.app.Activity;

String strClassName = Activity.class.getName(); // android.app.Activity
You can also get class information from a variable instance using the getClass() method of the Object class (which
is therefore inherited by all classes in Java):
String silly = "Silly String!";
Class someKindOfClass = silly.getClass();
String strSillyClassName = someKindOfClass.getName(); // java.lang.String
If you want to check the class of a variable, using instanceof is more appropriate. See the previous tutorial on
instanceof for more details.
Similarly, you might want to use the getClass() method with the this keyword to check the name of the class you’re
currently in and include this information as part of your debug logging to LogCat:
String strCurrentClass = this.getClass().getName(); // e.g. the current Activity
Log.v(strCurrentClass, "Debug tag is current class.");
Why Not To Use Reflection
As you’ve seen, reflection can be used to great effect, especially when you are unsure if a specific class or method
is available at compile time. Reflection does, however, have some drawbacks, including reduced performance and
the loss of the strong typing and safe coding practices enforced at compile time. It’s best to use reflection
sparingly, but do use it when needed.
Wrapping Up
Reflection is a powerful tool that Java developers can use to explore packages and APIs programmatically at
runtime. While reflection operations come at a cost, they give the developer the flexibility that is sometimes
essential for getting the job done. Android developers frequently use these simple reflection techniques to test for
the availability of specific classes, interfaces, methods, and fields at runtime, enabling them to support different
versions.

you’ve read about how iteration works in Java. Test your new skills with this challenge: five progressively difficult
exercises that help you solidify your knowledge of the Java programming language and Android development.
That’s right, Android too! You may need to refer to other Android tutorials that we’ve published on Mobiletuts+,
but if you can complete this challenge successfully you will know you are progressing nicely in your Java and
Android SDK understanding.

Setup
To prepare for this challenge, you’ll want to start with a basic Android application. Simply create an Android
application within Eclipse and edit its default Activity, specifically the onCreate() method, to test the code from
each of these challenges.
If what we’ve just asked of you is already too challenging, we would recommend taking a step back. Start with
some of the Android tutorials, such as Introduction to Android Development or Beginning Android: Getting
Started with Fortune Crunch. Once you’ve mastered setting up an Android project, return and try these exercises.
Getting Started: Working with String Array Resources
At first, we considered using a simple string array for you to use to complete these iteration challenges:
String aColors[] = {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};
However, there’s a much better way to store fixed arrays of values in Android: as resources. To create a string
array resource, you must first create String resources for each value. Next, create a String Array resource using
those String resources as elements. Use the <string-array> tag to combine String resources into an array resource
using child <item> tags for each element. For instance, here’s an array of colors inside an Android resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="red">Red</string>
<string name="orange">Orange</string>
<string name="yellow">Yellow</string>
<string name="green">Green</string>
<string name="blue">Blue</string>
<string name="indigo">Indigo</string>
<string name="violet">Violet</string>
<string-array name="colorsArray">
<item>@string/red</item>
<item>@string/orange</item>
<item>@string/yellow</item>
<item>@string/green</item>
<item>@string/blue</item>
<item>@string/indigo</item>
<item>@string/violet</item>
</string-array>
</resources>
To load this array resource in your Activity class, use the getStringArray() method of the Resources object. For
instance:
String aColors[] = getResources().getStringArray(R.array.colorsArray);
Challenge #1: Warm-Up Challenge
Now you’re ready to get started. Load the string array from the resources, as discussed above. Then, iterate through
the array’s contents using a for() loop. Print each string to the Android LogCat debug log using the Log.v()
method.
Find the answer to this challenge in the challengeOne() method of the downloadable project.
Challenge #2: Stretch Your Skills
Iterate the same array as Challenge #1, but use a different iteration mechanism. For example, use a while() loop
instead. Print each string to the Android LogCat debug log using the Log.v() method.
Find the answer to this challenge in the challengeTwo() method of the downloadable project.
Challenge #3: Reverse!
Iterate the same array backwards. Print each string to the Android LogCat debug log using the Log.v() method.
HINT: Challenge #2 can help.
Find the answer to this challenge in the challengeThree() method of the downloadable project.
Challenge #4: It’s All About Character
Next, go back to the for() loop you created in Challenge #1. Update it to print out the individual characters of each
String as well. This challenge will require an inner for() loop.
HINT: You can use the toCharArray() method of the String class to retrieve a character array.
The answer to this challenge is in the challengeFour() method of the downloadable project.
Challenge #5: Reflect on How Far You’ve Come
For this final challenge, you’re going to need a bit of understanding about Java reflection. Use reflection to iterate
through the declared fields within the android.os.Build class using a for() loop. Print each field name to the
Android LogCat debug log using the Log.v() method.
HINT: Our short tutorial on Java reflection will teach you everything you need to know to complete this challenge.
We’ve provided two different solutions for this challenge. The first solution assumes that the package is imported
and the compiler knows about the class. The second solution does not make this assumption. These solutions are
found in the challengeFiveA() and challengeFiveB() methods of the downloadable project.
Conclusion
Android developers use iteration techniques on a regular basis to solve coding problems. Iteration is frequently
used to iterate arrays, data structures like lists, or database content using cursors. Feel free to post your alternative
answers (or any questions) in the comments section.
In this tutorial, you’ll become familiar with the concept of inner classes in Java—those classes whose scope and
definition are encompassed within another class. You’ll also learn about anonymous inner classes, which are used
quite frequently when developing with the Android SDK.

Android applications are written in the Java, an object-oriented programming language. In this tutorial, you’ll learn
about inner classes, when and why to use them and how they work. You’ll also learn how to create new objects
dynamically using anonymous inner classes.
What You’ll Need
Technically, you don’t need any tools to complete this tutorial but you will certainly need them to develop Android
applications.
To develop Android applications (or any Java applications, for that matter), you need a development environment
to write and build applications. Eclipse is a very popular development environment (IDE) for Java and the
preferred IDE for Android development. It’s freely available for Windows, Mac, and Linux operating systems.
What is an Inner Class?
Most classes in Java are top-level classes. These classes, and the objects they define, are stand-alone. You can also
create nested classes in order to clearly encapsulate and define subordinate objects that only matter 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 functionality like iterators.
Here’s an example of a top-level class with two inner classes:
public class User {

// User fields, including variables of type LoginInfo and UserPreferences


// Misc user methods

class LoginInfo
{
// Login info fields
// Login/Logout methods
// Can access User fields/methods
}

class Preferences
{
// User preference fields
// Get/Set preference methods
// Reset preferences method
// Can access User fields/methods
}
}
In this example, the User class has two inner classes: LoginInfo and Preferences. While all user-related data and
functionality could be defined in the User class, using the inner classes to compartmentalize functionality can make
code easier to read and maintain. The inner classes LoginInfo and Preferences also have access to the
protected/private fields and methods available within the User class, which they might not otherwise have due to
security, if they were defined as stand-alone classes themselves.
It’s important to remember, though, that inner classes really only exist 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. Said another way, you would not be able to use or instantiate
the LoginInfo or Preferences classes except with an instance of the User class, but the inner classes could access
any fields or methods available in the outer class User, as needed.
Using Static Nested Classes
One particularly use for nested classes is static nested classes. A static inner class defines behavior that is not tied
to a specific object instance, but applies across all instances. For example, we could add a third nested class, this
time static, to the User class to control server-related functionality:
public class User {

// User fields, including variables of type LoginInfo and UserPreferences


// Misc user methods

class LoginInfo {}

public static class ServerInfo {}


{
// Server info applies to all instances of User
}
}
Because it’s public, this static nested class can be instantiated using the following new statement:
User.ServerInfo sInfo = new User.ServerInfo();
The outer class does not have to be instantiated to perform this instantiation, thus the use of the class name. As
such, a static nested class, unlike a non-static nested class (aka inner class) does not have access to members of the
outer class–they may not even be instantiated.
The Power of Anonymous Inner Classes
Android uses anonymous inner classes to great effect. Anonymous inner classes are basically developer shorthand,
allowing the developer to create, define, and use a custom object all in one “line.” You may have seen examples of
the use of anonymous inner class in sample code and not even realized it.
To create an anonymous inner class, you only provide the right-hand side of the definition. Begin with the new
keyword, followed by the class or interface you wish to extend or implement, followed by the class definition. This
will create the class and return it as a value which you can then use to call a method.
When we use an anonymous inner class, the object created does not get assigned a name (thus the term
anonymous). The side effect, of course, is that the object is used used just once. For example, it’s common to use
an anonymous inner class to construct a custom version of an object as a return value. For example, here we extend
the Truck class (assuming its defined elsewhere and has a field called mpg and two methods, start() and stop():
Truck getTruck()
{
return new Truck()
{
int mpg = 3;
void start() { /* start implementation */ }
void stop() { /* stop implementation */ }
};
}
Now let’s look at practical examples of anonymous inner classes used in Android.
Using an Anonymous Inner Class to Define a Listener
Android developers often use anonymous inner classes to define specialized listeners, which register callbacks for
specific behavior when an event occurs. For example, to listen for clicks on a View control, the developer must call
the setOnClickListener() method, which takes a single parameter: a View.OnClickListener object.
Developers routinely use the anonymous inner class technique to create, define and use their custom
View.OnClickListener, as follows:
Button aButton = (Button) findViewById(R.id.MyButton);
aButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// User clicked my button, do something here!
}
});
Using an Anonymous Inner Class to Start a Thread
Let’s look at another example. It’s quite common to define a new Thread class, provide the implementation of its
run() method, and start that thread, all in one go:
new Thread() {
public void run()
{
doWorkHere();
}
}.start();
Using a Named Inner Class
Using anonymous inner classes for listeners in Android is so common that it is practically second nature to do so.
Why, then, would you not want to use them? Let’s answer this through a hypothetical example.
Let’s say you have a screen that has 100 buttons on it (we did say hypothetical, right?). Now, let’s say each button,
when pressed, does the exact same thing. In this case, we’ll just listen for clicks and Toast the text from the View
object passed in (the text shown on the Button that was clicked):
Here’s pseudo code to do that:
Button[] buttons = getAllOneHundredButtonsAsArray();
for (Button button : buttons) {
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showToast(v.getText());
}
});
}
Short and elegant, so what’s wrong with it? At each iteration, a new OnClickListener object is instantiated. Since
each one is exactly the same, there is no good reason to create 100 of them. Instead, you can create a single,
named, inner class, instantiate it once, then pass that to the setOnClickListener() method. For instance:
class MyActivity extends Activity {

public void myMethod() {


MyClickHandler handler = new MyClickHandler();
Button[] buttons = getAllOneHundredButtonsAsArray();
for (Button button : buttons) {
button.setOnClickListener(handler);
}
}

class MyClickHandler implements View.OnClickListener {


public void onClick(View v) {
showToast(((Button) v).getText());
}
}
}
If you prefer anonymity, you can still assign an anonymous inner class to a variable and use that, like so:
class MyActivity extends Activity {

public void myMethod() {


View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
showToast(((Button) v).getText());
}
};

Button[] buttons = getAllOneHundredButtonsAsArray();


for (Button button : buttons) {
button.setOnClickListener(handler);
}
}
}
The method is up to you, but keep in mind the potential memory and performance issues that instantiating a bunch
of objects may have.
A Note on Nuances
This tutorial is meant to be an introductory guide to inner classes in Java. There are style considerations and
nuances when using inner classes in different and creative ways. Even beyond that, you can explore further to learn
more about the internal effects and marginal performance differences that can show up when you use nested
classes in different ways. All of this, however, is well beyond the scope of this tutorial.
A Quick Note On Terminology
Although we have tried to be consistent with the terminology on nested and inner classes, the terminology is not
always consistent from various online and offline resources. The following are a list of terms from the current
Sun/Oracle documentation, which is as good as any for being authoritative on Java:
• Nested Class: a class defined inside another class
• Static Nested Class: a static class defined inside another class
• Inner class: a non-static nested class defined inside another class
• Local Inner Class: a class defined within a method
• Anonymous Inner Class: an unnamed class defined within a method
Confused? You can use the java.lang.Class methods called isLocalClass() and isAnonymous() class on instantiated
classes to determine a couple of these properties. An Oracle blog entry attempts to clarify the situation a little, too,
with a nice Venn diagram.
Wrapping Up
The Java programming language supports nested classes, allowing the developer great flexibility in defining
objects. Inner classes can be used to organize class functionality or to define specialized behaviors that would
otherwise require the developer to expose class data and functionality that really shouldn’t be exposed. Static inner
classes can be used to define fields and functionality that apply across all instances of a class. Finally, anonymous
inner classes provide a useful shorthand for developers who want to create, define and use a custom object all at
once.
This quick lesson discusses a number of tips for working with inner classes in Java. This lesson is part of an
ongoing series of tutorials for developers learning Java in order to develop Android applications.

What are (Anonymous) Inner Classes?


In Java, classes can be nested within one another in order to organize data and functionality in an orderly fashion.
Anonymous inner classes are basically developer shorthand, allowing the developer to create, define, and use a
custom object all in one go. Anonymous inner classes are frequently used in Android to define handlers for
controls, define and launch new threads, and create and return custom objects in methods without cluttering code
with unnecessary setup.
Accessing Outside Variables with the Final Keyword
Sometimes you want to access information available outside of the inner class. Consider the following example.
You’ve got a screen with two controls: a Button and a TextView. Each time the user clicks on the Button control,
the TextView control is updated with the current time. Within the Activity class associated with this layout, you
could implement this functionality as follows:
Button myButton = (Button) findViewById(R.id.ButtonToClick);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
String strWhen = formatter.format(new Date());
TextView myTextview = (TextView)
findViewById(R.id.TextViewToShow);
myTextview.setText("Clicked at " + strWhen);
}
});
The above code will run and behave as expected. However, let’s say you really wanted to declare the TextView
control outside the inner class and use it for other purposes as well. Perhaps you’d try to do this instead:
TextView myTextview = (TextView) findViewById(R.id.TextViewToShow);
Button myButton = (Button) findViewById(R.id.ButtonToClick);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
String strWhen = formatter.format(new Date());
myTextview.setText("Clicked at " + strWhen);
}
});
Unfortunately, this won’t compile. Instead, you’ll get the compile error “Cannot refer to a non-final variable
myTextview inside an inner class defined in a different method”. As the error suggests, what you need to do is
make the TextView variable final, so that it is accessible within the inner class’s onClick() method:
final TextView myTextview = (TextView) findViewById(R.id.TextViewToShow);
Button myButton = (Button) findViewById(R.id.ButtonToClick);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
String strWhen = formatter.format(new Date());
myTextview.setText("Clicked at " + strWhen);
}
});
This code will indeed compile and run as expected.
Working with Final Variables in Java
By making the TextView variable final in the previous example, you’ve made it available to the anonymous inner
class (or any inner class defined within its scope, for that matter). Here are some other things to know about final
variables:
• You cannot change the value (r-value) of a final variable. For example, if you tried to assign the
myTextview variable to another control within the onClick() method of the inner class, you would get the
compile error “The final local variable myTextview cannot be assigned, since it is defined in an enclosing
type.”
• You can call a final variable’s methods, provided you have access. This is what allows us to make the call
to the TextView’s setText() method. This does not change the value of the variable myTextview, it simply
changes what is displayed to the screen—a subtle but important difference. (The reason for this is simply
that the reference to the object can’t change, but the object itself can change through its methods.)
• A final variable’s value need not be known at compile time, whereas a static variable is known at compile
time.
• The final keyword is often paired with the static variable (a field or variable tied to all instances of a class,
instead of a single instance) to create a constant for use within your application, as in: public static final
String DEBUG_TAG, used for LogCat logging purposes throughout your Activity.
Inner Classes and the “This” variable
In Java, you can use the special this reference to refer to the specific instance of an object. So what happens when
you have a class with an inner class, or, for that matter, an anonymous inner class? Well, the inner class can access
the special this instance of the enclosing class, and it has a this reference of its own as well. To access the this
instance for the inner class, simply use the this syntax. To access the this instance of the enclosing class, you need
to tack on the name of the enclosing class, then a dot, then this. For example:
MyEnclosingClass.this
Take a look at the full implementation of the anonymous inner class, as discussed above, in the full context of its
enclosing class, here called ClassChaosActivity:
package com.androidbook.classchaos;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ClassChaosActivity extends Activity {

public static final String DEBUG_TAG = "MyLoggingTag";


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final TextView myTextview = (TextView) findViewById(R.id.TextViewToShow);


Button myButton = (Button) findViewById(R.id.ButtonToClick);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");


String strWhen = formatter.format(new Date());
myTextview.setText("Clicked at " + strWhen);

Log.v(DEBUG_TAG, "this Class name: " + this.getClass().getName());


Log.v(DEBUG_TAG, "this extends interface named: " + this.getClass().getIn
terfaces()[0].getName());
Log.v(DEBUG_TAG, "this Enclosing class name: " +this.getClass().getEnclos
ingClass().getName());
Log.v(DEBUG_TAG, "this Is anonymous class? " + this.getClass().isAnonymou
sClass());

Log.v(DEBUG_TAG, "ClassChaosActivity.this Class name: " + ClassChaosActiv


ity.this.getClass().getName());
Log.v(DEBUG_TAG, "ClassChaosActivity.this Super Class name: " + ClassChao
sActivity.this.getClass().getSuperclass().getName());
Log.v(DEBUG_TAG, "ClassChaosActivity.this Is anonymous class? " + ClassCh
aosActivity.this.getClass().isAnonymousClass());
}
});

}
}
The log output for the button click proceeds as follows:
10:24 18:18:53.075: VERBOSE/MyLoggingTag(751): this Class name: com.androidbook.classchaos.ClassChaosActivity$1

10:24 18:18:53.085: VERBOSE/MyLoggingTag(751): this extends interface named: android.view.View$OnClickListener


10:24 18:18:53.085: VERBOSE/MyLoggingTag(751): this Enclosing class name: com.androidbook.classchaos.ClassChao
sActivity
10:24 18:18:53.095: VERBOSE/MyLoggingTag(751): this Is anonymous class? true
10:24 18:18:53.095: VERBOSE/MyLoggingTag(751): ClassChaosActivity.this Class name: com.androidbook.classchaos.C
lassChaosActivity
10:24 18:18:53.105: VERBOSE/MyLoggingTag(751): ClassChaosActivity.this Super Class name: android.app.Activity
10:24 18:18:53.105: VERBOSE/MyLoggingTag(751): ClassChaosActivity.this Is anonymous class? false
As you can see, the this keyword on its own refers to the “closest” class—the inner class. Although the inner class
is anonymous, Java does give it a number ClassChaosActivity$1 to keep track of it. While not useful to developers
per se, this shows that the anonymous inner class is treated like any other class internally. Meanwhile, we access
the enclosing class instance using the ClassChaosActivity.this syntax.
Conclusion
In this quick lesson you have learned several tips to help you use inner classes and anonymous inner classes more
skillfully. You learned that inner classes can access variables declared outside their scope, provided the variables
are marked as final and therefore unchangeable. You also learned about the special syntax related to the this
keyword when it comes to accessing inner class instance data as well as its enclosing class instance data.
This quick lesson covers Javadoc, a helpful tool for generating documentation from your Java source files. This
lesson is part of an ongoing series of tutorials for developers learning Java in order to develop Android
applications.

What is Javadoc?
Javadoc is a utility provided with the Java SDK that allows developers to generate code documentation from Java
source files. Development environments like Eclipse have built-in support for Javadoc and can generate searchable
HTML reference materials from Javadoc-style comments. In fact, the Android SDK reference is a form of Javadoc
documentation.

How Does Javadoc Work?


Javadoc documentation uses a combination of processing the source code (and inspecting types, parameters, etc.)
and reading special comment tags that the developer provides as metadata associated with a section of code.
A Javadoc-style comment must come just before the code it is associated with. For example, a Javadoc comment
for a class should be just above the class declaration and a comment for a method should be just above the method
declaration. Each comment should begin with a short description, followed by an option longer description. Then
you can include an number of different metadata tags, which must be supplied in a specific order. Some important
tags include:
• @author – who wrote this code
• @version – when was it changed
• @param – describe method parameters
• @return – describe method return values
• @throws – describe exceptions thrown
• @see – link to other, related items (e.g. “See also…”)
• @since – describe when code was introduced (e.g. API Level)
• @deprecated – describe deprecated item and what alternative to use instead
You can also create your own custom tags for use in documentation.
Generate Javadoc-style Comments in Eclipse
While you are writing code in Eclipse, you can generate a Javadoc –style comment by selecting the item you want
to comment (a class name, method name, etc.) and pressing Alt-Shift-J (Cmd-Shift-J on a Mac). This will create a
basic Javadoc-style comment for you to fill in the details.
Simple Javadoc Class Comments
Let’s look at an example. Here’s a simple Javadoc comment that describes a class:
/**
* Activity for loading layout resources
*
* This activity is used to display different layout resources for a tutorial on user interface design.
*
* @author LED
* @version 2010.1105
* @since 1.0
*/
1. public class LayoutActivity extends Activity {
Here’s what it will look like when you generate the Javadoc documentation:

Simple Javadoc Field Comments


Let’s look at an example. Here’s a simple Javadoc comment that describes a field within a class:
/**
* Debug Tag for use logging debug output to LogCat
*/
private static final String DEBUG_TAG = "MyActivityDebugTag";
Here’s what it will look like when you generate the Javadoc documentation:
Simple Javadoc Method Comments
Now let’s look at two examples of method comments. Here’s a simple Javadoc comment that describes a method
within a class:
/**
* Method that adds two integers together
*
* @param a The first integer to add
* @param b The second integer to add
* @return The resulting sum of a and b
*/
public int addIntegers(int a, int b)
{
return (a+b);
}
Now let’s look at a method that returns void, but throws an exception:
/**
* This method simply throws an Exception if the incoming parameter a is not a positive number, just for fun.
*
* @param a Whether or not to throw an exception
* @throws Exception
*/
public void throwException(boolean shouldThrow) throws Exception
{
if(shouldThrow == true)
{
throw new Exception();
}
}
Here’s what it will look like when you generate the Javadoc documentation for these two methods:

Generating Javadoc Documentation in Eclipse


To generate Javadoc code documentation in Eclipse, go to the Project menu and choose the “Generate Javadoc…”
option. This will launch a wizard that allows you to choose the projects to generate documentation for.
From this wizard, you should point Eclipse at the appropriate javadoc.exe command line tool (you’ll find it in your
JDK’s /bin directory). You can also configure some documentation settings, such as whether to document all code,
or only visible classes, members, etc. Finally, choose a destination for your documentation files.
Even without generating the Javadoc files, Eclipse will show the Javadoc-style documentation when you hover
over your methods and such, as shown in the figure below.
Learning More about Javadoc
You can find out more from the Javadoc reference at the Oracle website. There is also a helpful Javadoc FAQ
available.
Conclusion
In this quick lesson you have learned about Javadoc, a powerful tool used by Java developers to document source
code thoroughly for reference and maintenance purposes. Eclipse, the development environment used by many
Android developers, has built-in support for Javadoc.
In this tutorial, you’ll become familiar with one of the most important programming data structures (types) in Java
—the String. String variables can be used to store the textual (letters, numbers, symbols) data associated with a
program.

Android applications are written in the Java, a programming language. Java has a number of primitive data types
for different kinds of numbers (integers, floats, etc.), Boolean values, and single characters. In addition to storing
textual data as arrays or characters, Java also includes a powerful object class called String (java.lang.String),
which encapsulates textual data neatly and can be used to manipulate content. In this tutorial, you’ll learn how to
create, use and manipulate strings in different ways, including how to store them as Android project resources.
What You’ll Need
Technically, you don’t need any tools to complete this tutorial but you will certainly need them to develop Android
applications.
To develop Android applications (or any Java applications, for that matter), you need a development environment
to write and build applications. Eclipse is a very popular development environment (IDE) for Java and the
preferred IDE for Android development. It’s freely available for Windows, Mac, and Linux operating systems.
For complete instructions on how to install Eclipse (including which versions are supported) and the Android SDK,
see the Android developer website.

What is a String?
At the most fundamental level, Java programs are broken into functionality and data. Much human-readable data
comes in the forms of words, characters, punctuation, numbers and so on. Basically, anything the user can type on
a keyboard. Programmers call this storage of textual content “string data”, but the data itself can be stored using a
variety of different data structures, depending on your requirements:
• The Java String class (java.lang.String) is a utility class for storing string data that will not be modified.
• The Java StringBuilder class (java.lang.StringBuilder) is a utility class for storing string data that will be
modified; used when concurrency is not an issue.
• The Java StringBuffer class (java.lang.StringBuffer) is a utility class for storing string data that will be
modified; used when concurrency is an issue.
• An array of char primitives or Character (java.lang.Character) variables
• An array of byte primitives or Byte (java.lang.Byte) variables
• Various other data structures and object classes can be used to store string data
As you can see, there are numerous ways to store string data in Java. For example, the following Java variables
represent a string of vowel characters in different ways (as bytes, characters, Unicode representations or sub-
strings):
String strVowels = "aeiou";
char astrVowels[] = { 'a', 'e', 'i', 'o', 'u' };
byte abyteVowels[] = { 'a', 'e', 'i', 'o', 'u' };
byte abyteVowelsU[] = { '\u0061', '\u0065','\u0069','\u006F','\u0075' };
String uVowels = new String("\u0061\u0065\u0069\u006F\u0075");
CharSequence csVowels = (CharSequence) new String("aeiou");
StringBuffer sbVowels = new StringBuffer("a" + "e" + "iou");
StringBuilder sVowelBuilder = new StringBuilder();
sVowelBuilder.append('a');
sVowelBuilder.append("eio");
sVowelBuilder.append('\u0075');
The String class is the convenience class used most often, especially by beginners. You’ll also want to have a
passing understanding of the CharSequence (java.lang.CharSequence) interface, as it is often used when working
with Android resources.
Working with the String Class
The String class is available as part of the java.lang package, which is included within the Android SDK for
developers to use.
The String class represents an immutable (unchangeable) sequence of Unicode (16-bit encoding) characters,
appropriate for storing characters in any language (English, German, Japanese, and so on).
So what does this have to do with Android development? Well, strings are used to store content displayed on
application screens, or to store the input taken in from a user. Android developers are constantly loading, creating,
and manipulating string data. So let’s look at some of the stuff we can do with the String class.
Creating Strings
The String class has numerous constructors, for creating and instantiating string variables. String variables can be
set to empty using the null keyword. You can also set its content from byte, character, or other String data. For
example, here are some ways to create String variables for use within your applications (some are initialized from
the variables, like uVowels and sVowelBuilder, defined earlier in this tutorial):
String strVowels1 = "aeiou";
String strVowels2 = new String("aeiou");
String strVowels3 = new String(sVowelBuilder);
String strVowels4 = new String(sbVowels);
String strVowels5 = new String(uVowels);
String strVowels6 = new String(abyteVowels2);
String strVowels7 = new String(abyteVowelsU);
String strVowels8 = new String("a" + "e" + "iou");
String strVowels9 = new String( new char[]{'\u0061',
'\u0065','\u0069','\u006F','\u0075'});
String strVowels10 = new String(new byte[]{ '\u0061',
'\u0065','\u0069','\u006F','\u0075' });

Using Android String Resources


You can also load strings from Android application resources, provided you have stored them correctly. For
example, you can load the string resource for the application name into a String variable as follows:
String strAppName = getResources().getString(R.string.app_name);
This requires that the Android application in question contains a string resource named app_name somewhere in
the /res/values project directory hierarchy. For example, a file called /res/values/strings.xml which contains the
following XML string definition:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Android App Name!</string>
</resources>

Simple String Iteration


Now let’s look at some of the cool stuff you can do to String objects. First, let’s focus on the features available
within the String class itself.
It’s helpful to think of a String as a sequence of characters. As such, you sometimes want to iterate through its
contents, one character at a time. There are numerous ways to do this, but one simple way is to use a for() loop.
You can take advantage of the String’s length() method to determine how many characters you’ve got, and the
charAt() method to retrieve a specific character by its index, much like you would an array index. For example:
String strVowels = "AEIOU";
for (int i = 0; i < strVowels.length(); i++) {
char curChar = strVowels.charAt(i);
}

String Modifications: The Basics


As mentioned earlier, String variables are immutable, or unchangeable. That is not to say you cannot manipulate
the textual contents of a String variable, but each method that does so returns a new String variable. Some common
examples of String class methods that generate new String variables include:
• The concat() method is used to concatenate, or combine, two strings into a new String object. Note: You
can also use the + operator to create a new String object from parts as well.
• The format() method allows you to create parameterized string templates (a more advanced topic for future
discussion)
• The replace() and replaceFirst() methods are used to replace one character or substring with another
substring. The replaceAll() method supports regular expression pattern matching.
• The split() method is helpful for breaking a larger String into numerous substrings. For example, you could
break up a comma-delimited list into an array of String objects, one for each list item.
• The substring() method is used to extract only part of the original String object.
• The toUpperCase() and toLowerCase() methods are used to change the String’s case, especially useful for
normalizing strings.
• The trim() method is used to hack off (remove) any whitespace before or after the String contents.
Keep in mind that each of these methods allocates a new String object instance to store the result. The original
String variable remains unchanged.
String Modifications: Converting to Upper and Lowercase
Sometimes you want to convert your string to uppercase or lowercase. One reason you might want to change the
case of a string is to normalize the string to make case-insensitive searching or matching easier to implement.
String strUpperCaseVersion = strVowels.toUpperCase();
String strLowerCaseVersion = strVowels.toLowerCase();
Note that here you have created two new String variables for use. The original String variable, strVowels, remains
unchanged.
String Modifications: Splitting
Sometimes you want to quickly parse a string into substrings. You might do this to extract the individual words
from a sentence, or a delimited list of tags, etc. You can use simple regular expressions with the split() function for
this purpose. For example, the following code extracts the individual words (colors) from a String:
String someWords = "Red Orange Yellow Green Blue Indigo";
String aColors[] = someWords.split(" ");
If you were to print out the contents of the String array called aColors, you would see that:
aColors[0]=Red
aColors[1]=Orange
aColors[2]=Yellow
aColors[3]=Green
aColors[4]=Blue
aColors[5]=Indigo
Note that here you have created a new array containing 6 new String variables for use.
Simple String Matching
You can check if two strings match using the String class’s compareTo() method. This method will return 0 if, and
only if, the two strings are identical:
String strVowels = "AEIOU";
if(strVowels.compareTo("AEIOU") == 0)
{
// Strings match! (This code will execute)
} else {
// Strings don’t match!
}
Note that the compareTo() method is case-sensitive. Consider converting both sides of your comparison to one
case before comparing them, unless you are specifically looking for one case. If you don’t care about case, you can
also use the compareToIgnoreCase() method instead of the compareTo() method:
String strVowels = "AEIOU";
if(strVowels.compareToIgnoreCase ("aeiou")== 0)
{
// Strings match! (This code will execute)
} else {
// Strings don’t match!
}

Simple String Searching


Sometimes you want to search a string for a character or substring. There are many other ways to perform string
matching and searching, allowing you to build whatever search methods you desire. You can also hunt for specific
characters or substrings using the indexOf() and lastIndexOf() methods, check if a string begins or ends with a
substring using the startsWith() and endsWith() methods. Finally, the matches() method supports regular
expression matching.
Here we use the contains() method to determine if a specific substring exists:
if(strVowels.contains("IOU")==true)
{
// String contains IOU sub-string!
}
If you don’t care about case, use the compareToIgnoreCase() method instead:
String strVowels = "AEIOU";
if(strVowels. compareToIgnoreCase ("aeiou")== 0)
{
// Strings match! (This code will execute)
} else {
// Strings don’t match!
}
TIP: When implementing matching and searching functionality in your applications, don’t forget to do any
preprocessing string manipulation necessary to rule out upper/lower/mixed case string issues before searching.
User input normalization can be done as part of the input validation process, keeping your code as simple and
maintainable as possible.
Strings and Other Data Types
The String object is so fundamental to Java that every class, due to being derived from the root class called Object
(java.lang.Object), has a toString() method to create a useful string representation of their value. Classes that don't
have a reasonable string representation usually return some identifier or debug information as to the type of class.
Those that do have a reasonable string representation, such as a number string from an Integer object, return the
textual representation of the encapsulated number. When concatenated with a String, such as with the plus (+)
operator described above, the toString() method results are used by default. For example:
Integer iNum = new Integer(123);
String sText = "The number one-two-three = ";
String sFullText = sText + iNum;
String sFullText2 = sText + iNum.toString();
Both the strings (sFullText and sFullText2) have the same value, "The number one-two-three = 123". Many such
objects can also work in reverse. That is, they can parse a String representation and convert it to the native type the
object is representing. For instace, again with the Integer class, the parseInt() method can be used to get a new
Integer object based on the string representation.
Strings and Performance
As you’ve seen, strings can be used to great effect. String creation and manipulation does, however, have some
drawbacks. Imprudent String manipulation can have negative performance implications for your application. It’s a
basic design principle of Java to not create objects you don’t need. You can see that string manipulation and
modifications can result in a lot of String variables floating around. Here are some tips for good string usage:
• Don’t create String variables you don’t need, especially temporary ones.
• Use the StringBuilder and StringBuffer classes to generate string contents from the ground up.
• Review the performance suggestions available on the Android Developer website.
• Use static final String constants for String values known at compile time.
Wrapping Up
Strings are an important data type that Android developers use to store textual data. String data, whether it be a
sequence of characters, numbers, symbols, or some mix thereof, can be stored in a variety of ways, but the String
class is the primary utility class used for this purpose. The String class, and it’s helper classes like StringBuilder,
contain a robust set of methods for use with strings, allow their contents to be searched or modified.
11: Learn Java for Android Development: Date and Time Basics
In this tutorial, you’ll learn to work with dates and times in Java and within Android applications. Date and time
data can be determined, modified, and stored in a variety of ways.

Android applications are written in the Java, a programming language. Java has a number of primitive data types
for different kinds of numbers (integers, floats, etc.), Boolean values, and single characters. Java also includes
numerous classes for storing, formatting and modifying date and time data for use within your Android
applications. In this tutorial, you’ll learn how to determine the current date and time, store date and time data and
display it in a number of ways.
What You’ll Need
Technically, you don’t need any tools to complete this tutorial but you will certainly need them to develop Android
applications.
To develop Android applications (or any Java applications, for that matter), you need a development environment
to write and build applications. Eclipse is a very popular development environment (IDE) for Java and the
preferred IDE for Android development. It’s freely available for Windows, Mac, and Linux operating systems.
What is a Date or Time, Really?
First things first: the date and the time are basically two parts of the same piece of data (a point in time). When it
comes to storing dates and times in a computer, it can be helpful to think back to your first computer class and
recall that all data on a computer is made up of “ones and zeros”. Computers (and Android devices are no
exception) do not really have a sense of time like people do, but instead keep a numeric representation of the
current date or time (always ticking forward, one millisecond at a time) and then format this information in
different ways to suit specific purposes. After all, a single instant in time is interpreted differently depending upon
your time zone or location, whether or not you (or your area) recognize daylight savings, and various other factors.
Add to this fact that dates and times are displayed differently in different cultures and locales. For example, in the
United States, we often format our dates like this: April 6th, 1981, or 04/06/1981 whereas in Europe, the day
normally precedes the month, like this: 6 April, 1981, or 06/04/1981. Similarly, some countries have the concept of
AM and PM with a 12-hour, whereas others simply use a 24-hour clock.
Computers, including Android devices, calculate times and dates as a single number (a long)—which grows as
time passes. The number itself equates to the number of milliseconds elapsed since a specific date in the past. In
this case, the point in time at which the “time” started ticking is: midnight, January 1, 1970. This mechanism is
referred to as Unix time, or POSIX time.
What’s a Developer to Do?
Pop quiz! Which of the following strings correctly represents the 4th month of the (Gregorian) calendar year: A,
April, APR, Apr, 4, or 04? The answer? All of them. Already, working with dates and times seems a bit
complicated, doesn’t it? In fact, we did a quick perusal of all the Java reference books in our office (not
insubstantial) and very few cover dates and times in any substantial way. But don’t panic. Just accept the fact that,
as a developer, you will have to expend a bit of effort towards satisfying two goals:
1. Your External Goal: To allow the user to work with the date and time formats they are most comfortable with, or
at least familiar with.
2. Your Internal Goal: To keep your application code format-independent, so it works everywhere with little
hassle.
Now let’s talk a bit about each of these goals.
The External Goal: Be Flexible & Use Standard Controls
Have you ever noticed that few travel websites let the user manually enter date or time information? Instead, they
rely upon calendar pickers and fixed day, month and year dropdowns, or, at minimum, enforce a specific date
format (usually tied to your language/country, which they ask for in advance). From a user interface perspective,
your apps should honor date and time nuances, at least to some extent. However, you should also carefully
consider the methods in which the user can enter date and time information. By using standard date and time
pickers in your Android apps, such as DatePicker and TimePicker, you effectively limit the data users can input to
that which can be easily converted into appropriate date and time structures, without having to parse every known
format (not to mention its typos).

The Internal Goal: Keep Your Dates and Times Generic


From an internal code perspective, your apps should use a generic date/time representation that does not rely on
these nuances.
In Java, dates and times are stored in several ways, depending upon your requirements.
• The long type is a primitive data type capable of storing the number of milliseconds elapsed since a specific
point in time (Unix time).
• The Date class (java.util.Date) is a utility class for storing date and time in a way that can be reasonably
manipulated without having to constantly think about time in terms of milliseconds.
• The Calendar class (java.util.Calendar) is a utility class for working with different calendars, as well as for
manipulating date and time information in a variety of ways.
• The GregorianCalendar class (a subclass of java.util.Calendar) is used primarily for date manipulation in
the Western hemisphere, were we use a 12-month calendar, with 7 days to a week, and two eras (BC and
AD).
Determining the Current Date and Time
There are a number of ways to determine the current time on an Android device.
You can determine the raw date and time data using the static method provided in the System class
(java.lang.System):
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
This method relies upon the time that the device thinks it is, which may or may not be reliable. Another way to
determine the current date and time uses the default constructor for the Date class, which creates a Date object with
the current date and time:
Date anotherCurDate = new Date();
There are yet other ways to determine the true exact time—computers frequently check known time-keeping
servers to make sure everyone is “in sync”. This process is slightly beyond the scope of this tutorial, but suffice to
say, just requesting and receiving the correct time takes some time, which must then be accounted for before
synchronization can really be achieved.
(Note: Android devices that connect to cellular services tend to have locale accurate date and time information as
this may be used in communications with the radio towers.)
Creating Date and Time Variables from Scratch
Now what if you want to create a date or time variable from a specific date, like a birthday. Perhaps you know, just
off the top of your head, the number of milliseconds since 1/1/1970 midnight that represents your birthday. In my
case, that would be something like 229703700 milliseconds, or the morning of April 12th, 1977 (adjusted for
California time). However, as you can see, this is very cumbersome. Really, what you want to do is say: computer,
create me a date/time variable representing April 12th, 1977. That’s where the Calendar class comes into play:
GregorianCalendar bday = new GregorianCalendar(1977, Calendar.APRIL, 12);
You can use calendar objects to manipulate dates and extract interesting information about them. For example, you
could use the get() method to determine the day of the week that I was born upon:
int dayOfWeek=bday.get(Calendar.DAY_OF_WEEK); // Returns 3, for Tuesday!
Note that the months of the calendar are 0-based, so January is month 0, not month 1, and therefore April is month
3, not 4. Finally, you can extract a Date object from a Calendar date configuration using the getTime() method.
Formatting Date and Time Data
You can use the helper class called DateFormat (java.text.DateFormat) to convert raw date and time information
into different String formats (for different locales, etc.) or to parse String information into its appropriate date and
time bits for use in code.
For example, you can use the SimpleDateFormat class (a subclass of the DateFormat class) to create a custom
string containing date and time information. First, you must specify your format string, using the appropriate codes
for the different bits of information (see the SimpleDateFormat documentation for details on individual codes).
Then you apply that information to a specific date or time. For example:
Date anotherCurDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d 'at' hh:mm a 'in the year' yyyy G");
String formattedDateString = formatter.format(anotherCurDate);
If you were to print the String called formattedDateString, you might see something like: “Monday, December 6 at
08:34 AM in the year 2010 AD”.
Incidentally, you can also use the DateFormat and SimpleDateFormat classes to parse date and time strings into the
appropriate Date class. Hopefully, you won’t spend a lot of time parsing user-entered dates (which, generally, is
quite annoying), but having a parsing mechanism is useful. For example, you might want to parse timestamps from
an XML file, where you control or know the format of the timestamp in advance, and can therefore generate the
appropriate format string to parse with.
Displaying Date and Time Information to the User
There are numerous ways to display date and time information to the user. The way you choose depends upon your
requirements.
Perhaps the simplest way is to simply display a specific date or time as a properly formatted string. This method
makes the most sense for fixed dates or times, such as birthdays or events. Simply use the DateFormat utility class
to create the appropriate string and display it on the screen as you would any other text (such as within a TextView
control).
To show the time passing “in real time”, you can use either the AnalogClock (see figure) or DigitalClock controls.

Tip: Looking for a timer? Check out the Chronometer control.


Wrapping Up
Dates and times are important data types that Java developers inevitably must work with. Internally, devices store
date and time information numerically, but users interpret this information in different ways and using different
formats. Keep these nuances under control by limiting the ways users can input dates and times using built-in
picker controls and ensure your code uses a generic representation of this information, for example using one of the
many classes available for storing date and time information.
12: Learn Java for Android Challenge: Strings
You’ve read about how Strings work in Java. Test your new skills with this challenge: solve this String-based
puzzle to help you solidify your knowledge of the Java programming language and Android development. That’s
right, Android, too! You may need to refer to other Android tutorials here.
Setup
To prepare for this challenge, you’ll want to start with a basic Android application. Simply create an Android
application within Eclipse and edit its default Activity, specifically the onCreate() method, to test the code you
create for this challenge. Remember, you can use the Log.v() method to print output (including strings) to the
debug log. This is a quick and convenient way to display testing output for exercises such as this one.
If what we’ve just asked of you is already too challenging, we would recommend taking a step back. Start with
some of the Android tutorials, such as Introduction to Android Development or Beginning Android: Getting
Started with Fortune Crunch. Once you’ve mastered setting up an Android project, return and try these progressive
exercises.
A Progressive Challenge
This is a progressive challenge. If you follow each of the steps below correctly, you will solve a puzzle. Keep in
mind, there are numerous ways to approach this problem and therefore numerous solutions.
You can print out your progress to the Android debug log called LogCat using the Log.v() method.
Bonus: Extra points (not that you’re being graded) for those who catch the reference to this puzzle, and where it
comes from.
Step 1: Define Your String
For your first step, you’ll need to define a new text string for use in this challenge. You’ve got lots of options here.
For the many ways in which you can define strings in Java, see our String tutorial. The simplest method, of course,
would be to simply define a new variable of type String.
The contents of this string should be the following text:
Setec Astronomy
Step 2: Convert to Uppercase
For your next trick, you’ll want to convert the string to all uppercase letters.
Hint: If you’re stuck, check the methods available within the String class, as defined in the Android SDK
documentation.
Sanity Check: The contents of your new string should be the following text: SETEC ASTRONOMY
Step 3: Rearrange The Letters
Now things will get a bit more challenging…
As you may recall, a string is simply a sequence of characters. In this step, you want to rearrange the characters in
your uppercase string and add one extra character.
Think of your current string as a 0-based array of characters. Now rearrange the characters of your string into the
following sequence, where each number represents the current character index, dashes are used to separate each
index, and the asterisk (*) is used to represent a space character:
7-8-3-9-4-1-0-*-14-11-6-13-5-12-10-2
Hint: Remember that String variables cannot be changed. Seriously consider using StringBuilder.
to build up your new string contents from the specific characters of your source string.
Sanity Check: If you print out the resulting string, it should be:
STERCES YNAM OOT.
Step 4: Reverse Those Letters
You’re almost there! The only thing left to do is to reverse the characters in your string. Hopefully you used a
StringBuilder to build up your string from individual characters; it’s got a helpful method that can this job for you.
Print the resulting string. It should be clear if you’ve solved the puzzle.
Step 5: Tweak Your Solution (Optional Challenge)
It’s always a good idea to review your solution and improve it, perhaps making it slightly more elegant or flexible.
While this step is certainly not essential to solving the puzzle (especially as you’ve already done so), we suggest
you continue if you’ve found the previous steps reasonably straightforward.
Assuming you haven’t already, consider how you might define a String variable to represent the index sequence
discussed in Step 3.
String strSequence = "7-8-3-9-4-1-0-*-14-11-6-13-5-12-10-2";
Now, take the following steps:
1. Parse the string above into an array of Strings, one for each number or asterisk.
Hint: Check the String class method called split().
2. Create a loop and iterate through this array of strings and build the resulting string using a StringBuilder.
As part of this process, you will need to convert each String to the appropriate integer, or to a space
character.
Conclusion
Android developers use Strings all the time to store textual data for various purposes. Strings often need to be
manipulated in order to be used within your code. As always, there are many ways to solve these problems, so feel
free to post your alternative answers (or any questions) in the comments section. We have supplied a couple of
methods in the accompanying attachment.
13: Learn Java for Android Development: Java Shorthand
These quick tips discuss some of the most common Java shorthand techniques you’ll come across when you’re
getting started in Android development.

You’ll find these little code tidbits—which we are calling Java shorthand—used in the Android SDK sample code,
and just about every Android development book published at this time, not to mention online tutorials and
developer forums. None of these tips are Android-specific; they are simply Java techniques that routinely confound
beginners new to Java and Android, based upon the emails we receive from our readers.
Tip #1:Java’s Unary Operators (Increment/Decrement Variable
Shorthand)
Many developers like their code short and easy to read. Like some other programming languages, Java includes
unary operators for easily incrementing and decrementing variable values by 1.
In other words,
int counter = 1;
counter++;
counter--;
This code is equivalent to:
int counter = 1;
counter = counter + 1;
counter = counter – 1;
These unary operators can appear before (prefix) or after (postfix) the variable. The location of the operator
dictates whether the increment/decrement 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

Tip #2: Skipping Temporary Variables (Unnecessary Variables


Shorthand)
Java developers generally avoid creating variables they don’t really need. This is especially true of temporary,
ortemp ,variables that are used once to store the result of a statement, only to be abandoned.
Instead, Java developers frequently just use the statement to be evaluated as the “resulting” value itself. This is
seen often when it comes to return statements, but you’ll also see it in other places as well. For example, the
following verbose method uses a “temp” variable called sum to store the sum of two integers and then returns this
value:
int sumVerbose(int a, int b)
{
int temp = a + b;
return temp;
}
Many Java developers would simply skip the overhead and hassle of creating the temp variable, and just evaluate
the statement as part of the return statement, like this:
int sum(int a, int b)
{
return (a+b);
}
This style holds true for cases where the temp variable is only used once. If the method included further operations
on that value, it is usually prudent to use a well-named variable for code readability. In addition, you’ll often see
more “verbose” coding style in code that has a lot of debugging features.
Tip #3: The Java “this” Keyword and Chaining Methods
You will often see Java methods chained together. Frequently, these methods are called on the instance of the
current class (thus, the this keyword). Similar to the tip discussed above, the return values of each method are only
being used to access an underlying method. Therefore, the return value is not stored in a container value, instead
the underlying method is just called. For example:
InputStream is = getResources().openRawResource(R.drawable.icon);
This code is logically equivalent to the following:
Resources myAppResources = this.getResources();
InputStream is = myAppResources.openRawResource(R.drawable.icon);

Tip #4: Java’s Ternary Operators (If-Else Shorthand)


One conditional statement you will likely see will use Java’s ternary operator support. This is a shorthand way of
designing a simple If-Else statement using a conditional statement (which may or may not be encapsulated in
parentheses), followed by a question mark (?), then a statement to occur if the conditional is true, then a colon (:)
and another statement to occur if the conditional is false.
Here’s an example of a ternary operator in use:
int lowNum = 1;
int highNum = 99;
int largerNum = lowNum < highNum ? highNum : lowNum;
This is the logical equivalent of the following, much longer, code snippet:
int largerNum;
if(lowNum < highNum)
{
largerNum = highNum;
} else {
largerNum = lowNum;
}
This sort of Java shorthand is really only appropriate when your If-Else statement is simple. You’ll sometimes see
developers cram a lot of logic into one of these statements; we do not recommend this. Only use ternary operators
when they make your code easier to read, not harder.
Tip #5: Empty Statements (Infinite Loop Shorthand)
In Java, you can have empty statements simply by terminating a blank line of code with its semicolon. This trick is
often used to specify for() loop conditionals to create an infinite loop, like this:
for (;;) {
//Do something over, and over, and over again.
}
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.
Conclusion
It can be frustrating when developers new to Java encounter strange code syntax on their first day working with
Android— syntax that is not normally covered in the typical “Master Everything in Java in 20 Minutes” tutorial.
Now you know what some of these “shorthand” tricks look like, and what they mean. Whether or not you use them
yourself is up to you, but at least they won’t confound you when you see them in sample code! Good luck and feel
free to share some of your favorite shorthand Java code you come across in the comment section as well!
What is Android?
Android is an open source mobile operating system that combines and builds upon parts of many different open
source projects. What does this mean to you as a developer? You have access to the source code of the platform
that is running on the phone. This can help you better understand how interface controls and the various other
pieces work. If you happen to find a bug, you can also submit a patch for the issue, though this is a more advanced
practice. Google has also pulled together a large group of companies (called the Open Handset Alliance) that both
contribute to and use the Android OS in their hardware devices. This means that there is industry-wide support for
Google’s OS, promising wide adoption across well-known vendors.
Why Android?
There are many advantages to developing for the Android platform:
• Zero startup costs to begin development. The development tools for the platform are free to download,
and Google only charges a small fee to distribute applications on the Android Market.
• Freedom to innovate. The Android OS is an open-source platform based on the Linux kernel and multiple
open-source libraries. In addition to building applications to run on Android devices, developers are free to
contribute to or extend the platform as well.
• Freedom to collaborate. Android developers are not required to sign an NDA and are encouraged to
collaborate and share source code with each other. According to a survey by Black Duck Software, the
number of open source mobile apps and libraries grew at a rate of 168% from 2008 to 2009, faster on
Android than any other platform. This means more code that you can reuse in your own projects to bring
them to market much faster.
• Open distribution model. Very few restrictions are placed on the content or functionality allowed in
Google’s Android Market, and developers are free to distribute their applications through other distribution
channels as well.
• Multi-platform support. There are a wide variety of hardware devices powered by the Android OS,
including many different phones and tablet computers. Development for the platform can occur on
Windows, Mac OS or Linux.
• Multi-carrier support. A large number of telecom carriers currently offer Android powered phones.
Prerequisites before continuing with this article include:
• You must download and install the Eclipse IDE. Choose the “Eclipse IDE for Java Developers” option.
• You must download and install the Android SDK.
• Install the Android Development Tools (ADT) Eclipse plugin.
The Eclipse IDE
Eclipse is a complex, multi-language, and extensible Integrated Development Environment (IDE). The learning
curve can be steep, but the power of the environment can greatly increase your efficiency.
After opening Eclipse for the first time, select a workspace to save your project within. You will see an
introduction screen with multiple icons. Select the “go to workbench” option, and you will be presented with the
default project screen.
Assuming you have already installed the Eclipse ADT plugin, you will need to configure Eclipse for Android
development by manually setting the filepath for the Android SDK. To do this, select Eclipse > Preferences from
the main tool bar, and then select Android from the dialogue box that appears. Update the “SDK Location” option
to point to the directory where you installed the SDK. You should now have the IDE configured for Android
development.
It is important to note that Eclipse uses something called “perspectives” to group commonly used tasks. Switching
perspectives will switch out parts of the menu and toolbars, and will show and hide views related to them.
Perspectives can be opened by clicking on the Open Perspective button or by choosing Window > Open
Perspective. Some perspectives that you will use frequently include Java, Debugging and DDMS.
The Java Perspective
The Java perspective is the default perspective in Eclipse, and it is where you will probably spend most of your
time.

Among the most important views in this perspective is the Package Explorer view, by default located on the left
hand column of the workbench. This view is an overview of your entire project. It also shows the states of
individual files with regard to compile issues, version control, etc.
Another important view in the Java perspective is the Problems view, by default located in the bottom center panel
of the workbench. This is where you will find compile warnings and errors listed. You can double-click an item to
be taken directly to the error in the Java or XML file.
The DDMS Perspective
DDMS is short for Dalvik Debug Monitor Server, which communicates with the low-level services of a device or
emulator. Switch to the DDMS perspective now by selecting Window > Open Perspective > DDMS.

The Devices view, located in the left column of the workbench, is where you will see any Android devices
available to your computer. This includes both phones attached to your machine and running emulators. Under
each device, you will see all the running processes. There are toolbar buttons on the view for launching the
debugger on a process, getting information about heaps and threads, stopping processes, and taking screenshots.
The Emulator Control view, also in the left column, lets you do the following:
• Set the status of the voice connection.
• Set the status, speed and latency of the data connection.
• Simulate an incoming call or SMS from a supplied phone number.
• Provide a simulated set of points for the GPS via a latitude/longitude point, or GPX/KML file.
Using the File Explorer view, accessible as a tab at the top-right of the center column, you can browse the
file system of a device. For an emulator or a rooted phone, you will have access to the private directories
/data and /system. For non-rooted phones, you will only have access to /sdcard.
The Debugging Perspective
The debugging perspective will provide in-depth information about your applications. Switch to the
debugging perspective now by selecting Window > Open Perspective > Debug.

The Debug view will show you the running apps being analyzed, and, when stopped on a breakpoint or
exception, the call stack of the application as well. The Variables view displays the contents of any local
variables at the current breakpoint.
The LogCat view in the lower right hand corner displays all logging output using the android.util.Log class.
You can filter based on tags, or different log levels such as debug, information, error, etc.
Your First Application
To begin creating an Android application, switch back to the Java perspective and select File > Menu >
Android Project. Doing so will launch the application creation wizard, and you will be prompted to enter
meta-information about your project in three categories: Contents, Build Target, and Properties.
Name the application “DemoApp” and leave the Contents section with all the default values.
The Build Target section defines the version of the SDK that our demo app will be compiled against. For
this tutorial, choose API level 4 (Android 1.6) because it will run on a wide range of hardware and the API
will allow us to handle different screen resolutions.
Next is the Properties section, which provides the wizard with more information about what classes
to generate and what they should be named. The Application Name setting will be displayed under the
application icon, as well as the application’s title bar when launched. The Package name provides the base
Java namespace for your generated classes. In order to create a default activity, make sure Create Activity
is checked and provide an activity name. The last option is the Min SDK version. This value determines
what version of Android needs to be on a phone in order for this application to be installable. This is
generally set to the same API level that you chose under Build Target.
Once you enter all this information and click Finish, you will have a basic “Hello World” application that is
almost ready to run on a phone or an emulator. Before we setup an emulator and run the application, take a
few minutes to examine the standard template content generated:
The AndroidManifest.xml file
The AndroidManifest.xml file provides metadata about your application that the Android OS will need to
run the app properly. The name of the application, used for both the app icon and the activity titlebar, and
the app icon are defined under Application Attributes. You will notice that the Name field doesn’t actually
contain the name text, but “@string/app_name” instead. This is a string reference and can be used anytime
a string is expected. The actual string text is then defined in one of the XML files found under the
res/values folder. The app creation wizard generated a file there called strings.xml.
The Application Nodes section is where all the activities are defined for the application. Our app’s single
activity is called MainActivity and listed here.
The /res folder
The res folder is where most application resources are stored. The main content categories include
drawables, layouts, and values.
Drawables are generally bitmaps images in the form of .PNGs. Drawables can also be nine-patch images,
which are .PNGs with special data in the image that help Android do a better job when stretching the
image. Nine-patch images can be created with the nine-patch tools in the SDK, or with an image creation
tool like Photoshop.
Layouts are where you define your screens. To view the XML for the layout on screen, click the main.xml
tab.
Values are where you define (in XML) your globally used colors, dimensions, strings and styles. The
strings.xml file allows you to add and edit values for your project.
The /gen folder
This is where code is generated for all the resources defined in your res folder. This is how you can access
layouts and controls defined within your code.
The /src folder
The src folder contains all of your custom source code, grouped into packages. Packages are simply there to
help categorize your source code into logical (and manageable) groups.
The /assets folder
The assets folder is a place to store miscellaneous files you need to access in your code as raw data. All
files in the res folder have methods to load the specific types, whereas the only way to load something from
assets is to programmatically open it as a file.
Creating an Android Virtual Device
Virtual devices make it possible to run and test your code without owning an actual Android phone. Since
there are several different version of the OS you can target, you will eventually need to create multiple
versions of virtual devices, but for now, we’ll create one using API level 4 (1.6). You can do this via the
AVD Manager. From the main toolbar, select Window > Android SDK and AVD Manager.

Once you’ve opened the manager and are viewing your list of virtual devices, click the “New” button to
create your virtual device.
I generally name my virtual devices using the OS version number along with the preset resolution that I
choose, so in this case, 1.6-hvga. It’s good to also create an SD Card for the emulator which I usually set to
16MB, unless I know I will need more space. Click the Create AVD button, and you will see your device
listed.

Go ahead and start the virtual device by selecting it and clicking the “Start” button.
Running & Debugging Your First App
Eclipse, along with the Android Developer Tools, offers a great environment for debugging applications.
For debugging, you’ll use both the Debugging and the DDMS perspectives. The debugging perspective will
be used for stepping through code, viewing values of variables, and setting breakpoints. The DDMS
perspective will be used to control the emulator, view threads, and view memory allocation.
Since this is our first time running the application, we need to create something called a run configuration.
Run configurations are the settings that Eclipse will use to run (or debug) your application. Each
application can have multiple configurations. One might be set up to always deploy and run on an attached
phone, and another could be setup to only run in a specific emulator instance. At this point, disconnect your
phone if you happened to have it attached to your machine so you can see the app run on the emulator first.
To create the run configuration, select DemoApp in the Package Explorer, then choose Run > Run from
the main menu. In the next dialog, choose Android Application and click OK. The emulator that we created
earlier should launch. When the emulator first starts up, it may appear with the lock screen; just click menu
to be taken to your new app. You should now see the text “Hello World” on screen!

Our next step will be to set a breakpoint. Open the MainActivity.java file by double-clicking it in the
Package Explorer. It is located under /src > com.demo.demoapp. Next, on the line that contains:
view plaincopy to clipboardprint?
1. "super.onCreate(savedInstanceState)"
double-click in the gray column to the left of the line (where you see the blue circle in the screenshot
below). If you were successful, there should now be a blue circle indicating the breakpoint.

Now switch to the debugging perspective by selecting Window > Open Perspective > Debug . To debug
the application, select Run > Debug.
In the Debug view, you should see a list of items under DalvikVM/Thread. This is the call stack since we
are now stopped at the breakpoint we set earlier. The Variables view will show all local variables at the
current breakpoint. You can expand the item “this” to see all the values of our MainActivity instance.
Finally, LogCat will display all logging information coming from the emulator.
To continue running the app, you can use the toolbar on the Debug view (as seen in the screenshot above),
or choose the same actions from the run menu. Choose Run > Resume to let the app continue running.
Conclusion
This tutorial took you through the various parts of Eclipse and ADT that you need to be familiar with to
begin Android development. Although we didn’t cover the details of the application source code, it is
important to start with a strong understanding of the tools you will use every day during development. In
coming articles, we will continue to dig deeper into writing progressively complex applications and
creating a compelling UI.

You might also like