Java Basics for Android Development
Java Basics for Android Development
Introduction to Java
Shane Conder & Lauren Darcey on Sep 13th 2010 with 39 comments
Tutorial Details
This entry is part 1 of 13 in the series Learn Java for Android Development
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.
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 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.
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.
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:
If you simply read 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).
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.
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, [Link]. The
Android Manifest file is a file required by all Android applications, which you use to define
configuration details about your app.
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. [Link]). 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:
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:
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:
A class like Fish could then implement the Swimmer interface (using the implements keyword)
and provide implementations of the swimming behavior:
view plaincopy to clipboardprint?
Wrapping Up
Wow! You’ve just embarked on a crash-course in Java for Android development. We’ve covered
a pretty intense amount of material here, so let things settle for a bit before moving on to the next
lesson of this tutorial series. In Lesson 2, we switch our focus to the nitty-gritty details of Java
syntax.
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. Good
luck!
Tutorial Details
Technology: Java with Android Focus
Difficulty: Beginner
Estimated Completion Time: 45-60 minutes
This entry is part 2 of 13 in the series Learn Java for Android Development
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.
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.
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:
1. /* MULTILINE
2. COMMENT */
You can also provide comments after code on a single using //. For example:
view plaincopy to clipboardprint?
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:
view plaincopy to clipboardprint?
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:
1. int i = 5;
You’ve also got your arithmetic operators like +, -, *, /. Remember to use parenthesis to force the
order of operations as necessary:
view plaincopy to clipboardprint?
1. int result = (a + b) / c;
Finally, you have your typical unary operators, which allow you to modify a single variable with
a simple statement:
view plaincopy to clipboardprint?
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 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:
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):
view plaincopy to clipboardprint?
1. int[] aiPowersOfTwo;
2. aiPowersOfTwo = new int[4];
3. aiPowersOfTwo [0] = 1; // 2^0=1
4. aiPowersOfTwo [1] = 2; // 2^1=2
5. aiPowersOfTwo [2] = 4; // 2^2=4
6. aiPowersOfTwo [3] = 8; // 2^3=8
1. int iVal = 1;
2. Integer integ1= new Integer(iVal);
3. float f = [Link]();
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.
view plaincopy to clipboardprint?
For a list of common Java data types, the Android reference includes documentation for the
[Link] package. You can also find the common input/output objects in the [Link] package.
For more complex data structures like lists, queues, stacks, dates, and times, appropriate classes
are in the [Link] 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 [Link] package.
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
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.
== 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 (||):
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:
If you want to provide alternative code to run if the condition is not met, then use the else clause
with the if() statement:
view plaincopy to clipboardprint?
If you want to handle more than two cases, you can use cascading if-else-if-else statements, like
this:
view plaincopy to clipboardprint?
1. if(iVar==0) {
2. // variable is zero
3. } else if (iVar > 0) {
4. // variable is a positive number
5. } else {
6. // variable is a negative number
7. }
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.
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.
1. int numItemsToProcess = 3;
2. while(numItemsToProcess > 0)
3. {
4. // process an item
5. numItemsToProcess--;
6. }
If you want to evaluate the conditional loop expression AFTER the first iteration, you can use a
do-while loop instead:
view plaincopy to clipboardprint?
1. do
2. {
3. // check for items to process, update numItemsToProcess as required
4. // process item, updated numItemsToProcess
5. } 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:
view plaincopy to clipboardprint?
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).
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:
Now, let’s try to use this class and pass a Cat object into some functions and see what happens:
view plaincopy to clipboardprint?
Finally, let’s call these methods and see how they act upon Cat object instances:
view plaincopy to clipboardprint?
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!
Tutorial Details
This entry is part 3 of 13 in the series Learn Java for Android Development
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:
1. if(iVar==0) {
2. // variable is zero
3. } else if (iVar > 0) {
4. // variable is a positive number
5. } else {
6. // variable is a negative number
7. }
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:
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:
1. void checkforTextView(View v)
2. {
3. if(v instanceof TextView)
4. {
5. // This is a TextView control
6. } else {
7. // This is not a TextView control
8. }
9. }
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.
Learn Java for Android Development:
Working with Arrays
Shane Conder & Lauren Darcey on Sep 29th 2010 with 3 comments
Tutorial Details
This entry is part 4 of 13 in the series Learn Java for Android Development
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:
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:
1. int aNums[] = { 2, 4, 6 };
Or, you could store non-primitive types like Strings (or any other class) in an array:
view plaincopy to clipboardprint?
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:
view plaincopy to clipboardprint?
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:
view plaincopy to clipboardprint?
1. 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:
view plaincopy to clipboardprint?
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:
view plaincopy to clipboardprint?
1. String [] aStopLightColors;
2. aStopLightColors = new String[3];
3. aStopLightColors[0] = new String("red");
4. aStopLightColors[1] = new String("yellow");
5. aStopLightColors[2] = new String("green");
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:
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:
1. int aNums[] = { 2, 4, 6 };
2.
3. for (int i = 0; i < [Link]; i++) {
4. String strToPrint = "aNums[" + i + "]=" + aNums[i];
5. }
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:
view plaincopy to clipboardprint?
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.
Tutorial Details
This entry is part 5 of 13 in the series Learn Java for Android Development
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.
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.
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 ([Link]) 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:
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.
For example, the following code iterates through the declared constructors of a class:
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.
For example, the following code iterates through the declared fields of a class:
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:
view plaincopy to clipboardprint?
1. String sClassName = "[Link]";
2. try {
3. Class classToInvestigate = [Link](sClassName);
4. String strNewFieldName = "EXTRA_CHANGED_PACKAGE_LIST";
5. Field newIn22 = [Link](strNewFieldName);
6.
7. } catch (ClassNotFoundException e) {
8. // Class not found
9. } catch (NoSuchFieldException e) {
10. // Field does not exist, likely we are on Android 2.1 or older
11. // provide alternative functionality to support older devices
12. } catch (SecurityException e) {
13. // Access denied!
14. } catch (Exception e) {
15. // Unknown exception
16. }
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.
For example, the following code iterates through the declared methods of a class:
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.
For example, the following code checks the security modifiers of a class:
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.
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
@[Link]() when this code is run on Android 2.2:
Similarly, you could simply check for the existence of a specific annotation, such as deprecation,
by its type:
view plaincopy to clipboardprint?
1. if([Link]([Link]) == true)
2. {
3. // Class is deprecated!
4. }
1. import [Link];
2. …
3. String strClassName = [Link](); // [Link]
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):
view plaincopy to clipboardprint?
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:
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.
Tutorial Details
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.
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:
view plaincopy to clipboardprint?
To load this array resource in your Activity class, use the getStringArray() method of the
Resources object. For instance:
Extra points if you use the shorthand version of for() loops, discussed in Learn Java for Android
Development: Working with Arrays.
Find the answer to this challenge in the challengeOne() method of the downloadable project.
Find the answer to this challenge in the challengeThree() method of the downloadable project.
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.
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.
Best of luck!
Learn Java for Android Development: Inner
Classes
Shane Conder & Lauren Darcey on Oct 26th 2010 with 4 comments
Tutorial Details
This entry is part 7 of 13 in the series Learn Java for Android Development
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.
For complete instructions on how to install Eclipse (including which versions are supported) and
the Android SDK, see the Android developer website.
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.
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.
Because it’s public, this static nested class can be instantiated using the following new statement:
view plaincopy to clipboardprint?
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.
1. Truck getTruck()
2. {
3. return new Truck()
4. {
5. int mpg = 3;
6. void start() { /* start implementation */ }
7. void stop() { /* stop implementation */ }
8. };
9. }
Now let’s look at practical examples of anonymous inner classes used in Android.
1. new Thread() {
2. public void run()
3. {
4. doWorkHere();
5. }
6. }.start();
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:
view plaincopy to clipboardprint?
If you prefer anonymity, you can still assign an anonymous inner class to a variable and use that,
like so:
view plaincopy to clipboardprint?
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:
Confused? You can use the [Link] 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.
Tutorial Details
This entry is part 8 of 13 in the series Learn Java for Android Development
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.
For a thorough discussion of nested and inner classes, including anonymous inner classes, see
our tutorial called Learn Java for Android Development: Inner Classes
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:
view plaincopy to clipboardprint?
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:
view plaincopy to clipboardprint?
1. [Link]
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:
view plaincopy to clipboardprint?
1. package [Link];
2.
3. import [Link];
4. import [Link];
5.
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11. import [Link];
12.
13. public class ClassChaosActivity extends Activity {
14.
15. public static final String DEBUG_TAG = "MyLoggingTag";
16. /** Called when the activity is first created. */
17. @Override
18. public void onCreate(Bundle savedInstanceState) {
19. [Link](savedInstanceState);
20. setContentView([Link]);
21.
22. final TextView myTextview = (TextView) findViewById([Link]);
23. Button myButton = (Button) findViewById([Link]);
24. [Link](new [Link]() {
25. public void onClick(View v) {
26.
27. SimpleDateFormat formatter = new SimpleDateFormat("h:mm:ss a");
28. String strWhen = [Link](new Date());
29. [Link]("Clicked at " + strWhen);
30.
31. Log.v(DEBUG_TAG, "this Class name: " + [Link]().getName());
32. Log.v(DEBUG_TAG, "this extends interface named: " + [Link]().getInte
rfaces()[0].getName());
33. Log.v(DEBUG_TAG, "this Enclosing class name: " +[Link]().getEnclosi
ngClass().getName());
34. Log.v(DEBUG_TAG, "this Is anonymous class? " + [Link]().isAnonymo
usClass());
35.
36. Log.v(DEBUG_TAG, "[Link] Class name: " + ClassChaosAc
[Link]().getName());
37. Log.v(DEBUG_TAG, "[Link] Super Class name: " + ClassCh
[Link]().getSuperclass().getName());
38. Log.v(DEBUG_TAG, "[Link] Is anonymous class? " + Class
[Link]().isAnonymousClass());
39. }
40. });
41.
42. }
43. }
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 [Link] 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.
Tutorial Details
Difficulty: Beginner
Estimated Completion Time: 15-20 minutes
Technology: Java with Android Focus
This entry is part 9 of 13 in the series Learn Java for Android Development
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:
You can also create your own custom tags for use in documentation.
1. /**
2. * Activity for loading layout resources
3. *
4. * This activity is used to display different layout resources for a tutorial on user interface
design.
5. *
6. * @author LED
7. * @version 2010.1105
8. * @since 1.0
9. */
10. 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:
1. /**
2. * Debug Tag for use logging debug output to LogCat
3. */
4. private static final String DEBUG_TAG = "MyActivityDebugTag";
Here’s what it will look like when you generate the Javadoc documentation:
1. /**
2. * Method that adds two integers together
3. *
4. * @param a The first integer to add
5. * @param b The second integer to add
6. * @return The resulting sum of a and b
7. */
8. public int addIntegers(int a, int b)
9. {
10. return (a+b);
11. }
Now let’s look at a method that returns void, but throws an exception:
view plaincopy to clipboardprint?
1. /**
2. * This method simply throws an Exception if the incoming parameter a is not a positive
number, just for fun.
3. *
4. * @param a Whether or not to throw an exception
5. * @throws Exception
6. */
7. public void throwException(boolean shouldThrow) throws Exception
8. {
9. if(shouldThrow == true)
10. {
11. throw new Exception();
12. }
13. }
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 [Link] 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.
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.
Tutorial Details
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 ([Link]), 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.
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 ([Link]) is a utility class for storing string data that will
not be modified.
The Java StringBuilder class ([Link]) is a utility class for storing string
data that will be modified; used when concurrency is not an issue.
The Java StringBuffer class ([Link]) 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 ([Link]) variables
An array of byte primitives or Byte ([Link]) 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):
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 ([Link]) interface,
as it is often used when working with Android resources.
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):
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/[Link] which contains the following XML string definition:
view plaincopy to clipboardprint?
1. <?xml version="1.0" encoding="utf-8"?>
2. <resources>
3. <string name="app_name">My Android App Name!</string>
4. </resources>
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:
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.
Note that here you have created two new String variables for use. The original String variable,
strVowels, remains unchanged.
If you were to print out the contents of the String array called aColors, you would see that:
view plaincopy to clipboardprint?
1. aColors[0]=Red
2. aColors[1]=Orange
3. aColors[2]=Yellow
4. aColors[3]=Green
5. aColors[4]=Blue
6. aColors[5]=Indigo
Note that here you have created a new array containing 6 new String variables for use.
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:
view plaincopy to clipboardprint?
1. if([Link]("IOU")==true)
2. {
3. // String contains IOU sub-string!
4. }
If you don’t care about case, use the compareToIgnoreCase() method instead:
view plaincopy to clipboardprint?
1. String strVowels = "AEIOU";
2. if(strVowels. compareToIgnoreCase ("aeiou")== 0)
3. {
4. // Strings match! (This code will execute)
5. } else {
6. // Strings don’t match!
7. }
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.
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.
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.
Tutorial Details
This entry is part 11 of 13 in the series Learn Java for Android Development
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.
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.
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.
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 ([Link]) 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 ([Link]) 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 [Link]) 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).
You can determine the raw date and time data using the static method provided in the System
class ([Link]):
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.)
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:
view plaincopy to clipboardprint?
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.
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.
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.
Tutorial Details
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.
Setec Astronomy
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
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:
1. 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.
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.
1. Parse the string above into an array of Strings, one for each number or asterisk.
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.
Best of luck!
Tutorial Details
This entry is part 13 of 13 in the series Learn Java for Android Development
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.
In other words,
1. int counter = 1;
2. counter++;
3. counter--;
This code is equivalent to:
view plaincopy to clipboardprint?
1. int counter = 1;
2. counter = counter + 1;
3. 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:
view plaincopy to clipboardprint?
1. int counter = 0;
2. Log.i(DEBUG_TAG, "The counter value is ="+counter++); // prints 0
3. Log.i(DEBUG_TAG, "The counter value is ="+counter); // prints 1
4. Log.i(DEBUG_TAG, "The counter value is ="+counter--); // prints 1
5. Log.i(DEBUG_TAG, "The counter value is ="+counter); // prints 0
6. Log.i(DEBUG_TAG, "The counter value is ="+(++counter)); // prints 1
7. Log.i(DEBUG_TAG, "The counter value is ="+--counter); // prints 0
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:
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:
view plaincopy to clipboardprint?
1. int sum(int a, int b)
2. {
3. return (a+b);
4. }
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.
1. InputStream is = getResources().openRawResource([Link]);
1. int lowNum = 1;
2. int highNum = 99;
3. int largerNum = lowNum < highNum ? highNum : lowNum;
This is the logical equivalent of the following, much longer, code snippet:
view plaincopy to clipboardprint?
1. int largerNum;
2. if(lowNum < highNum)
3. {
4. largerNum = highNum;
5. } else {
6. largerNum = lowNum;
7. }
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.
1. for (;;) {
2. //Do something over, and over, and over again.
3. }
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!
Understanding Java syntax is fundamental to Android application development as it is the primary language used for creating Android apps. Familiarity with Java syntax enables developers to efficiently utilize Android's robust libraries and APIs, crucial for effective app development. For those familiar with other programming languages, learning Java syntax allows translation of existing programming concepts into Android development, enhancing their skill set and enabling them to create versatile applications with pre-established programming principles .
Java inner classes provide a way to logically group classes that are only used in one place, enhancing encapsulation. They can access members of the enclosing class, making them suitable for implementing adapter functionality such as iterators, which often need to traverse and interact with many members of another class. In Android development, inner classes, including anonymous inner classes, are frequently used to implement event listeners and callbacks, enabling a tighter coupling and easier access to the variables and methods of the containing class .
Iteration techniques in Java are fundamental for processing collections of data, which is a common requirement in Android development. Common scenarios include iterating over arrays and lists, which are frequently used to manage views, contacts, messages, or any data structure involving multiple items. Iteration is also applied when accessing elements in databases via cursors. By automating repetitive tasks, such as updating UI elements with data or processing user input, iteration simplifies code and enhances application performance and functionality .
Android developers utilize anonymous inner classes to handle events more efficiently by allowing them to define behavior directly inline without the need for a separate named class. This approach simplifies code related to event handling, such as listening to user interface events like button clicks. Using anonymous inner classes reduces boilerplate code and improves readability by keeping the event-handling logic close to where the events are triggered. This encapsulation is particularly useful in streamlining listener implementations within an activity or fragment .
For-loops and while-loops in Java both facilitate iteration, but they have distinct uses. A for-loop is ideal when the number of iterations is known ahead of time, as it condenses the loop initialization, condition, and iteration expression within one line, enhancing readability. In contrast, while-loops are suitable for scenarios where the loop should continue until a particular condition changes, offering more control over loop execution when the number of iterations isn't predetermined. In Android development, choosing between them depends on the specific use case and readability demands, ensuring that the most intuitive structure is applied for maintaining and future-proofing code .
Substrings in Java are often replaced to modify parts of the text within a string for various purposes, such as data cleaning, formatting, and preparing text for output or storage. The use of regular expressions in methods like replaceAll() enhances this process by allowing more complex pattern matching and transformations. Regular expressions provide powerful tools to identify specific substrings based on patterns, which can then be replaced, making string manipulation efficient and adaptable to complex requirements without manually coding all conditions .
The Java String class provides several methods that can be leveraged to transform and normalize user input for consistent processing in Android applications. Methods like toUpperCase() and toLowerCase() ensure uniform casing, facilitating case-insensitive searches and comparisons. The trim() method removes unwanted whitespace, aiding in sanitizing input data. Additionally, the split() method can divide input into manageable components based on delimiters, making it easier to parse and process forms or queries. Together, these transformations help maintain data consistency and reliability in application logic .
Packages are crucial in Java for organizing classes and interfaces because they help avoid naming conflicts and allow for better modularization of code. In complex projects like Android development, where the scale of application code can be quite large, packages enable developers to group related classes and interfaces together logically. This organization improves code maintainability and readability by providing a clear structure and hierarchy, making debugging and updating more manageable .
Understanding Java's immutable strings is crucial for Android developers because it significantly influences how memory resources are managed. Since strings in Java cannot be altered once created, each modification operation results in new object creation, which can lead to increased memory consumption. Developers need to be cautious with operations like concatenation in performance-critical applications to avoid unnecessary memory overhead. Efficient use of string builders or buffers for concatenation operations is recommended to optimize performance and resource usage, which is especially important in resource-constrained environments like mobile devices .
Java's reflection plays a significant role in Android development by enabling runtime inspection and manipulation of classes, methods, and fields. This capability allows developers to create objects, invoke methods, and access fields dynamically, which is essential for frameworks that require loose coupling between components or support for plugin architectures. Reflection is particularly useful in Android for tasks like dependency injection, where object creation and configuration are handled dynamically, promoting flexibility and decoupling in application design .