BlackBerry Java Application Development
Beginner’s Guide
The book teaches how to write rich, interactive, and smart BlackBerry applications in
Java. It expects the readers to know Java but not Java Mobile or the BlackBerry APIs.
This book will cover Uiprogramming, data storage, programming network, and Internet
APiapps. As we move on, you will learn more about the BlackBerry’s device features,
such as messaging, GPS, multimedia, contacts and calendar, and so on. This book also
helps you build your own applications to illustrate the platform and the various
capabilities that developers can use in their programs.
What This Book Covers
Chapter 1, Introducing BlackBerry Application Development gets you started by talking
about the capabilities of a BlackBerry smartphone and what kind of things can be done
with these capabilities with a custom application. It talks about the other tools which are
available and why writing native Java applications by using the BlackBerry SDK is the
most powerful and practical approach to developing applications. Finally, it covers how
to select which version of the SDK to use and when you might want to use an older
version of the SDK instead of the latest.
Chapter 2, Installing the development Environment steps you through the process of
installing the proper versions of Java and Eclipse. This chapter talks about when to install
additional versions of the SDK and how to do so through the Eclipse over-the-air update
tool as well as how to install them manually.
Chapter 3, Getting Familiar with the Development Environment starts off the learning
process by importing an existing sample application—the standard “Hello World”
application. After importing the project, the chapter will go over this simple application
line-by-line. Afterwards, you will run the application in the simulator and then introduce
a bug into the application so that you can debug it as well.
Chapter 4, Creating your first BlackBerry Project is where you create a new project from
scratch. This chapter demonstrates how you accomplish this using Eclipse and the
various wizards that are available within it. It also demonstrates how you can create a
simple, but complete application quickly using the User Interface (UI) elements provided
by the framework.
Chapter 5, Learning the Basics about the UI creates an application to demonstrate each
of the Uielements that are available to you when using the BlackBerry SDK. This
sample application demonstrates how to set and retrieve data from each field and
discusses when each field should be used according to the BlackBerry development
guidelines. By demonstrating each field, you will get a complete understanding of the
capabilities of each field.
Chapter 6, Going Deeper into the UI picks up where the previous chapter leaves off by
demonstrating how to use some of the advanced fields, such as lists and trees. It also
covers navigation between screens, displaying dialogs, and common patterns used in the
BlackBerry SDK. By the time you are done with this chapter, you will be well equipped
to create the entire Uifor an application.
Chapter 7, Storing Data jumps right into how to use the data storage tools of the SDK
and when it is appropriate to use each one. This covers the Java standard RMS, the
BlackBerry-specific PersistentStore, and even how to access the removable media cards
that are available on some devices.
Chapter 8, Interfacing with Applications shows you how to take advantage of one of
most powerful features available to a BlackBerry application. Each BlackBerry device
comes with standard applications that you can interface with. These include the address
book, calendar, and even the messaging applications. Being able to tightly integrate an
application with these can make it even more valuable and useful to the end user.
Chapter 9, Networking wades into the complex, but an important area of how to make an
application networking aware. Here, you will discover what transports are available, how
to open connections , and how to send data through them. The sample also demonstrates
how to communicate with a simple web service and parse the resulting XML data.
Chapter 10, Advanced Topics covers two distinct, but powerful topics. The first topic is
how to utilize the built-in GPS receiver that is built in to some smartphones in order to
get location information. You will learn about the various methods that can be used to get
location information and how to do some common calculations using these coordinates.
The other topic covered in this chapter covers how to use alternate entry points so that a
single project can be used to launch multiple applications. Because these applications
share a common project, they can share code and even memory.
Chapter 11, Wrapping It All Up finishes the book with tasks that commonly are done last,
such as localization with language resource files and code-signing your application so
that it can be installed on real devices. You will also learn what it takes to distribute your
new application through the BlackBerry App World marketplace.
Interfacing with Applications
Now that we’ve covered some of the basics of application development it’s
time to expand our horizons a bit and look at interfacing with other BlackBerry
applications. You can create many great applications that don’t do anything
more complex than interfacing with the user and storing data. Sometimes
though, developing an interesting application means doing something more
or something special with the existing applications on the device. When you
think about development from this point of view, there are suddenly a lot more
applications that can be created than before.
The BlackBerry handhelds come pre-loaded with many great programs to help
make a person more productive. While messages may be the most common
reason a person will purchase a BlackBerry, the other Personal Information
Management (PIM) applications oft en quickly become essential as well.
As a developer, you cannot ignore the other applications on the handheld. The
more integrated an application can be with these standard applications, the
bett er the user experience will generally be. Our TipCalc application is very
specialized, and one of the few that works well without integrating with other
applications. More oft en than not though, any applications that you create will
benefit from some level of integration.
Not only can you interface with these applications by adding or editing content
in them, you can also listen for events that allow you to react to things that
happen. Some of the applications even allow you to add menu items and other
“active content” to them. That’s a lot to talk about, so we’ll just focus on some
of the most common tasks to get you started in this chapter.
Introducing PIM
The first area that we will take a look at is the Personal Information Management, or PIM
applications and data. PIM applications are a rather generic name for a group of tools that
manage your personal information, especially as it relates to your handheld. This could be
stretched to include a lot of things, but it generally means your messages, contacts, and
scheduling information that help you to manage your life. In BlackBerry terms it means the
Messages, Address Book, Calendar, Tasks, and Notes.
Access to the PIM data in the BlackBerry SDK is provided through the JSR-75 specification,
which is a Java standard. Like many of the Java standards in the BlackBerry SDK, there
are also BlackBerry-specific extensions available that expand the basic classes with new
BlackBerry-specific functionality.
Like many of the other standards we find in Java, JSR-75 implements a factory patt ern where
one class, in this case the PIM class, is used to create objects for the other more specific
types of PIM data. The PIM class can basically do only one thing and that is to retrieve a
PIMList object that contains a bunch of specialized PIMItem objects.
Why is all so generic?
All of these PIM classes may seem very generic and you would be absolutely correct. They
are generic and they are supposed to be that way. PIM data is a very generic concept so the
implementation is very generic as well. Also, because it is a Java standard, it needs to be
fl exible enough to accommodate any system that it might be implemented on.
A perfect example of this kind of fl exibility is the BlackBerry PIN field. The BlackBerry PIN is
an entry in your address book and therefore, it should be included in the PIM data that you
get. However, a PIN is a BlackBerry-specific concept and no other device out there will use it.
You can’t really expect the Java standard to include specialized fields for every possible piece
of data that some device may have or want to include. The answer to this is to present PIM
data in a key-value pairing so that it is fl exible enough to handle every possible scenario.
A key-value pairing is a somewhat technical term to describe the patt ern for storing values
based on a static key. Or, more simply, if you know the proper key you can access the value.
The fl exible part is that the PIM object storing all of the values does not need to know about
each specific value or provide any special mechanism for accessing each specific value. All
access is done through generic methods, which also require the key.
The difficulty in using this kind of approach is that the keys must be common knowledge. In
addition, simple numeric keys do not support self-documenting code or even easily readable
code. Keys that are string values off er a lot of advantages—in that the keys are much more
readable, but the possibility for mistakes is very great because you don’t have the compiler
to help ensure that only correct keys are used.
To help solve these issues there are derived classes for each type of PIM item. While you can
do nearly everything by using the generic classes that a derived class would off er, iwouldn’t
recommend it. These classes are here to make your code easier to write and read, and
should be used.
PIMLists
As we said early on, the PIM class is used primarily to retrieve a PIMList object for a
specific kind of PIM item, that is, address book contact, calendar event, and so on. For
each of these types, there is also a specialized class that you can use instead of the generic
PIMList class. Classes such as ContactList, EventList, and ToDoList off er a
specialized version of the more generic PIMList class. These specialized classes are also
part of the Java standard and should be preferred because they off er a few more methods
which are specific to that kind of data.
There are BlackBerry-specific versions of these classes as well. Therefore, the
BlackBerryContactList class is the BlackBerry-specific version of the ContactList,
which is in turn a specialized version of PIMList for contact data. Generally speaking, you
will want to use the BlackBerry-specific versions of PIMList classes when making
your applications.
PIMItems
A PIMItem is the generic representation for any piece of PIM data. Just like there are specific
versions of the PIMList, there are also specific versions of the PIMItem class for each
kind of PIMItem. Contact, Event, and ToDo are all specific versions of a PIMItem for
that kind of PIM data. As you might expect, there are BlackBerry-specific versions as well.
BlackBerryContact, BlackBerryEvent, and BlackBerryToDo all exist to extend and
further specialize the standard Java classes.
These specialized classes aren’t as specialized or easy to use as one might expect though.
Providing a method called getFirstName might be really useful, but unfortunately,
you will find nothing of the sort. The specialized classes off er few methods for accessing
data. Instead, they provide static values for the keys used to set and retrieve data from
the PIMItem class . Remember, earlier we noted that one drawback to using this kind of
key-value pairing was that keys were sometimes not clear and that you could not expect
help from the compiler. By providing each key value in the specialized class, both of these
goals are accomplished. The name of the key value now provides a readable name and the
compiler will fl ag an error if there is a typo or problem with the constant value being used.
Another aspect of PIMItem is that each value that an item has a specific type associated
with it as well. Some of these are obvious, such as the start date of an event using a Date
type. Some of them, such as the Name field of a Contact that requires an array, are not.
Some fields can be given a subtype as well, such as the Phone field. With the subtype you
can specify what kind of phone number it is: home, work, or mobile. Furthermore, some of
the fields can have multiple occurrences while others cannot. A good example of this is the
Email field in a Contact. A contact is allowed to have up to three e-mail addresses, but there
is no subtype associated with them like there is with phone numbers. The bott om line to
all this is that the PIM items have a defined structure to them and they won’t allow just any
value to be put into a field. The documentation plays a big role here in understanding this
because there are no field-specific methods to provide some additional assistance in the
proper way to access each field.
Laying the ground work
Still, this is all rather abstract because you haven’t seen any real code samples yet, so let’s
get into some code! For this chapter, you will build an application that someone will use to
request some time off from their manager. This is definitely one of those applications that
just can’t be done without interfacing with other applications on the handheld! To make
getting started a litt le easier we will take the starter TimeOff application from the code
bundle and add to it throughout this chapter.
The first task to undertake is one to help make testing and debugging easier. Remember,
you will be working on the simulator, which is essentially a brand new device and which can
be oft en reset. That means you don’t have any of your contacts there! You will need some
contacts later, so to get started let’s add a menu item to the application that will create a few
contacts that you can later use to test with.
Time for action – creating test contacts
- Modify the _AddTestAddressesAction menu item in the
TimeOff project to look like the following completed code. - Then add this line to the constructor to make the menu
item available when you run the application.
protected MenuItem _AddTestAddressesAction = new MenuItem(
“Add Test Data”, 800000, 50)
{
public void run()
{
PIM pimInstance = PIM.getInstance();
try
{
// TODO: Create test contacts
BlackBerryContactList contacts =
(BlackBerryContactList)pimInstance.openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
BlackBerryContact newContact1 =
(BlackBerryContact)contacts.createContact();
BlackBerryContact newContact2 =
(BlackBerryContact)contacts.createContact();
String[] names = new
String[contacts.stringArraySize(BlackBerryContact.NAME)];
names[BlackBerryContact.NAME_FAMILY] = “Smith”;
names[BlackBerryContact.NAME_GIVEN] = “John”;
if (contacts.isSupportedArrayElement(Contact.NAME,
Contact.NAME_SUFFIX))
{
names[BlackBerryContact.NAME_SUFFIX]=”Jr”;
}
newContact1.addStringArray(
BlackBerryContact.NAME,
BlackBerryContact.ATTR_NONE,
names);
names[Contact.NAME_FAMILY] = “Doe”;
names[Contact.NAME_GIVEN] = “John”;
if (contacts.isSupportedArrayElement(Contact.NAME,
Contact.NAME_PREFIX))
{
names[Contact.NAME_PREFIX] = “Dr.”;
}
newContact2.addStringArray(Contact.NAME, Contact.ATTR_NONE,
names);
//TODO: Add Phone numbers
//TODO: Add Email Addresses
//TODO: Add Addresses
newContact1.commit();
newContact2.commit();
}
catch (PIMException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
this.addMenuItem(_AddTestAddressesAction);
What just happened?
This is the first of several baby steps as you work towards the goal of creating some test
contacts in the address book in the simulator. As the address book in the simulator doesn’t
have any entries to begin with, and can be erased frequently, doing this provides you with
a way to quickly and easily create or recreate the contacts you will use later on for testing
other parts of this application. It also happens to be a great way to demonstrate how to add
contacts.
This first baby step does only a few things. First, it gets a PIMList object for contacts and
then creates two new contacts. Aft er this it sets the name of each one and finally commits
the records into the address book. These steps make sense at a high level, but let’s take a
look at the details.
The first step is to get an instance to the PIM object, which is done through a static method
in the PIM class called getInstance.
PIM pimInstance = PIM.getInstance();
Once you have an instance of PIM, the next step is to get a list of contact items using the
openPIMList method on the instance you just retrieved. This same method is used to
get a list of any kind of PIM item so you must specify the type of data to get as one of the
parameters. The PIM class off ers constant values for every kind of PIM item, so in this case,
use the constant PIM.CONTACT_LIST. As you plan to add new contacts, the next parameter
needs to be the constant PIM.READ_WRITE so that you have write permissions. It’s always
good practice to request the minimum amount of permissions that you need, so if your
application doesn’t change or add data to the list you should simply use the
PIM.READ permission.
As we touched on earlier, this method returns a generic PIMList type so you also
have to cast it to the appropriate specialized type. If a list type of CONTACT_LIST has
been specified, you can cast the resulting PIMList to either of the available specialized
classes—ContactList or BlackBerryContactList. As long as your application is a
BlackBerry-specific application, there is no good reason to use the less specialized class of
ContactList. Instead, you should always use BlackBerryContactList.
BlackBerryContactList contacts =
(BlackBerryContactList)pimInstance.openPIMList(PIM.CONTACT_LIST, PIM.
READ_WRITE);
The next step is to create a couple of new contacts that you will start to populate. This
is done through the createContact method available on the ContactList class.
Again, you need to cast the resulting objects to the proper type. The createContact
method returns a contact, but again you’ve chosen to use the more specialized version of
BlackBerryContact instead. Because this is all being executed on a BlackBerry handheld,
you can always cast a contact to a BlackBerryContact safely. The same is true for each of
the Java specialized classes and their corresponding BlackBerry specialized class.
BlackBerryContact newContact1 = (BlackBerryContact) contacts.
createContact();
BlackBerryContact newContact1 = (BlackBerryContact) contacts.
createContact();
The next segment of code sets the name att ribute of the newly created contacts. Notice that
this is done through an array of String objects instead of individual methods. This isn’t
something that is done to be more efficient, it is done this way because it must be; there is
no other way.
We mentioned before about each field in a PIMItem having a type associated with it. Most
of the field types are basic String or Date type fields, but NAME is more complicated than
most of the other fields. The NAME field is defined as a StringArray because there are
many parts to a name and you want to be able to set each part separately. There aren’t very
many fields of this type used, but this is probably one of the most important. You can only
set the NAME field as a whole unit, so if only one part of the name needs to be changed the
entire name field must be replaced.
To work with the name, you must first create a string array of the proper size. There is no
constant value for this as it may vary with the SDK version. Instead, you must first get the size
by using the stringArraySize method on the ContactList and then construct a new
array by using the returned value.
String[] names = new String[contacts.stringArraySize(BlackBerryConta
ct.NAME)];
Once you have an array of the proper size each part of the name is set by indexing the array
by using the NAME constant from the Contact class.
names[BlackBerryContact.NAME_FAMILY] = “Smith”;
names[BlackBerryContact.NAME_GIVEN] = “John”;
In this example, you also want to add another name part but are not sure whether the field
is supported in this system. Not all fields are supported and not all of the name subfields are
supported either. You can test to see whether a field or a subfield is supported by using the
isSupportedField or isSupportedArrayElement method s in the ContactList class.
In this case, you test to see if the suffix is supported, and then set the suffix if so.
if (contacts.isSupportedArrayElement(Contact.NAME,
Contact.NAME_SUFFIX))
{
names[BlackBerryContact.NAME_SUFFIX]=”Jr”;
}
This step is very important if you want to use the same code for multiple platf orms. Each
system can support the fields it chooses. In this case, the suffix is NOT supported and if you
were to step through this code in the debugger, you would see that the code to set the suffix
is skipped over. Later on, when you test this application, you will also see that the suffix was
not added to the contact.
Other platf orms may implement it diff erently. You could just assume each of the name
subfields are supported and set the field without testing to see if it is supported. In the
BlackBerry SDK, unsupported fields are just quietly ignored. This can lead to confusion
wondering why a field doesn’t appear in the Address Book application, but it won’t cause an
error.
The next step is to actually add the NAME field to the contact. Up until this time you’ve simply
been building an array in memory with all of the proper values.
newContact1.addStringArray(
BlackBerryContact.NAME,
BlackBerryContact.ATTR_NONE,
names);
Notice that the method addStringArray doesn’t give any indication about what field is
being added, but only what type of data is being added. All of the PIMItem methods are like
this. Remember, this class is designed to be generic. The first parameter is the field indicator,
which is one of the many constants that are defined in the Contact class. In this case, we
use the BlackBerryContact class . Because BlackBerryContact derived from Contact,
all of the constant values are accessible. The BlackBerryContact class does define
some constants that are BlackBerry-specific, such as PIN. For this field you must reference
the constant value from BlackBerryContact because the Java standard Contact class
does not define it. Partly for this reason, isuggest always referencing constant values from
BlackBerryContact because all of the constant values will be available through this class.
The method addStringArray was chosen because that is the type of data that you are
adding. The NAME field is defined as a string array and so you must use the addStringArray
method because it corresponds to the data type of the field.
Once you finish with the first contact, the code starts building the NAME string array to add
a second contact. For demonstration sake, all of the constant values that are referenced are
done so using the Contact class instead of the BlackBerryContact class.
names[Contact.NAME_FAMILY] = “Doe”;
names[Contact.NAME_GIVEN] = “John”;
if (contacts.isSupportedArrayElement(Contact.NAME,
Contact.NAME_PREFIX))
{
names[Contact.NAME_PREFIX] = “Dr.”;
}
newContact2.addStringArray(Contact.NAME, Contact.ATTR_NONE, names);
Also, notice that the second contact applies a prefix to the name and tests to see if it is
supported in the same way as you did for the suffix when adding the previous contact.
However, the prefix is supported and if you were to step through this method in the
debugger, you would see that the prefix is being set properly.
The last step you have to do is to commit the data that has been added to the contact.
newContact1.commit();
newContact2.commit();
Simply creating a new contact is not enough; you must commit the changes in it by using the
commit method. Creating a contact and then never committing it will not have any eff ect on
the Address Book application. It simply won’t be shown in the list. That’s the whole point of
this exercise, so you have to make sure and commit the changes once they are all done.
At this point, if you were to run the application and select the menu, you would see two new
contacts added to the Address Book application in the simulator. They would show up as Dr.
John Doe and John Smith. There would be only names with these contacts because that is all
that you’ve added so far.
In the example code that you just stepped through there was one mistake that could have
proven to be very serious. Did you catch it? You are reusing the names array to set the
names of both contacts. This is actually risky, but it happens to work out in this case. If the
SUFFIX field had been supported then your Dr. John Doe would have actually been Dr. John
Doe Jr. because the array was not reset before it was used again. If you had changed the
order around, John Smith would have been Dr. John Smith. This might have lead to a bug
that could have been tough to track down, so keep it in mind.






October 1, 2010
BlackBerry