Creating your First BlackBerry Project

Exclusive offer: get 50% off this eBook here
BlackBerry Java Application Development

BlackBerry Java Application Development — Save 50%

Build and deploy powerful, useful, and professional Java mobile applications for BlackBerry smartphones, the fast and easy way.

$23.99    $12.00
by Bill Foust | July 2010 | Beginner's Guides Java

In this article by Bill Foust, author of BlackBerry SDK 4.5 Java Application Development: Beginner's Guide, you will create a new project from scratch. This article 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.

We will create a simple standalone application to calculate the tip of a bill at a restaurant. The initial application will be very simple and will be like the first step on a project. As you progress through the rest of this article the application will grow and become more robust. Specifically, we will look at:

  • How to create a BlackBerry project using Eclipse
  • How to add the essential classes an Application and a Screen
  • Setting up a screen with fields
  • Creating and using menus

(For more resources on BlackBerry, see here.)

So, without any further words, let's get to work!

Choosing the SDK version

Remember that the first step is to choose the SDK version to use. For this project we want to choose the lowest possible SDK version, which is 4.2.1. This is because this application is so simple that it will not need to use any of the newer features of more recent versions of the SDK.

By choosing a lower version, more models of handheld can be used to run this application. Conversely, choosing a higher SDK version means that fewer models of handhelds can run the application. Therefore, you should choose the lowest version of the SDK that still supports the features you require in order to support as many devices as possible. We will go through the steps of actually applying this later on, but for now, the choice is made and we are ready to move on.

Creating a new project

You need to create a new project for your new application. The IDE makes it very simple to get started, but because you are creating a BlackBerry project you have to be careful. Let's get started and see what I mean.

Time for action – creating a new project

  1. You can create a new project by clicking on File | New | Project... option in the menu bar (not the File | Java Project menu item).

    BlackBerry Java Application Development Tutorial

  2. The New Project dialog gives you many choices for which type of project to create.
  3. You want to create a BlackBerry project, of course. Expand the BlackBerry folder in the tree and then select the BlackBerry Project node. When that is done click on the Next button.

    BlackBerry Java Application Development Tutorial

  4. Enter TipCalc as the name of the application and click on the Finish button to create the new project.

    BlackBerry Java Application Development Tutorial

What just happened?

These three steps are all that is needed to create a BlackBerry project in Eclipse.

You were told earlier that choosing New | Java Project was not the right thing to do. This is because the wizard that you get from choosing this menu item is the Swiss Army Knife wizard that will set up any kind of project for Eclipse. It is powerful, complicated, and not for beginners. Because of this, we just won't use it at all. The BlackBerry Project option is much easier to use, you just have to remember to use the New | Project... option instead of the New | Java Project option.

Once you have chosen the right menu item, the New Project dialog is shown. Apparently, it is possible to have so many project types available that finding the one you want can be a challenge. The text field at the top of the dialog will filter the tree below to include only projects whose name matches the filter test. In our case though, the BlackBerry project is right near the top and easily accessible so there really isn't a need for the search feature.

The last step of the wizard prompts you to enter the name of your new application. Project names are used as a directory name but are not used in code so they can have some special characters, such as a space, which would otherwise be invalid for code. If you try to provide a name that is invalid the wizard will show a warning about the name to indicate the name is not valid.

BlackBerry Java Application Development Tutorial

Below the Project name text box is a checkbox indicating to use the default workspace location. By leaving the box checked the new project will be placed in a directory named after the project name under the directory set as the workspace. You can change the location where the new project files are stored by unchecking the Default location checkbox and then entering a new location in the edit field provided.

Adding a package to the new project

Next, you will create a new package for the application to use. A Java package is a container for the objects in your application and is used to prevent conflicts if the classes you create happen to have the same name as another class in the same project or even the system classes. Packages are equivalent to namespaces in C# and Visual Basic .NET (VB.NET).

Adding a package to the project in this way is a minor housekeeping task, but is also an overall good technique because it forces you to choose your package name up front before creating any code. In Java, the naming convention for a package is to use your Internet domain name in reverse—almost like you were creating a new server. In this case, we will use the package name com.rimdev.demo.tipcalc. The package name can be any valid Java name and doesn't have to follow these conventions.

Time for action – creating a new project

  1. Add the package by right-clicking on the src folder in the Package Explorer and then selecting New | Package.

    BlackBerry Java Application Development Tutorial

  2. After selecting the menu the New Java Package wizard is shown. This small wizard is here only to collect the folder where the package files will be and the name of the package itself. Because you selected the src folder to begin with, that part is already filled in so you need to specify only the name of the package.
  3. Enter the package name com.rimdev.demo.tipcalc into the Name field and then click on Finish to create the package.

BlackBerry Java Application Development Tutorial

What just happened?

At this point you have an empty project that is ready to start being used. You've taken the BlackBerry application project that you had before and added a package to the src directory in preparation for creating the actual source files (which will come next).

The project tree is expanded slightly to include the package you just created under the src directory—the directory whose icon looks like a little mail parcel. Creating a package in your project doesn't result in any actual source files being created. Instead, it sets up the project so that when you do create files later on they will be created with package definitions already included in them.

BlackBerry Java Application Development Tutorial

Start at the beginning

Every application must have a starting point, and for BlackBerry applications it is at a method named main. The use of the name main goes all the way back to the C programming language, if not further. At that time, simply making a method named main was enough to be able to run an application. However, because Java is an object-oriented language, you can't just make a method named main. In Java, all methods must be in a class, and this includes the method main as well.

In addition to the main method all BlackBerry applications must contain an object derived from Application as well. As both the Application-derived class and the main method are required, it is standard practice to include the main method in the same class as your Application.

Application and UiApplication

As we just said, every BlackBerry application must contain a class derived from Application. The Application class contains the bare essentials for interacting with the BlackBerry operating system. If an application displays a User Interface (UI) then the bare essentials in the Application class are not enough. Instead, you should use UiApplication—the derived class that handles the special processing needed to interact with the user as well as the operating system.

So, the next step is to create a class derived from UiApplication and that contains the main method to serve as the starting point of your BlackBerry application.

Time for action – adding the UiApplication class

  1. To create this starting class right-click on the package you just created in the project and select New | Class.

    BlackBerry Java Application Development Tutorial

  2. First, give the class a name; enter TipCalcApplication into the Name field.

    BlackBerry Java Application Development Tutorial

    The next step is to set the superclass for your new class. The superclass is another name for a base class, or the class from which your new class will be derived. Eclipse offers a strong browser tool to quickly and easily find the class.

  3. Click on the Browse button next to the Superclass field . This dialog is aware of all of the classes in the libraries and allows you to choose the proper one. By default, the class java.lang.Object is set as the superclass. Replace java.lang.Object with uiapplication. Notice that as you do so, other class names appear in the list below, but once it is completely entered only the net.rim.device.api."ui.UiApplication" class is shown. Also notice that even though you entered the name in lowercase and did not enter the complete package name, the filter found the correct class with the correct casing. Click on OK to select this class.

    BlackBerry Java Application Development Tutorial

  4. Back at the New Java Class dialog there is one more setting to make and that is to check the public static void main(String args[]) option. This creates a stub main function that is used to initiate the application. Use this checkbox only when creating UiApplication objects ; no other classes need them. Check the public static void main(String[] args) checkbox so the wizard will generate the main function.

    BlackBerry Java Application Development Tutorial

  5. Finally, click on Finish and see the new class in the project.

What just happened?

You just created the first class for use in your new application! Well, to be more accurate you used Eclipse to set up a new class with some standard elements based on how you filled out the dialog. You could have done the same thing by simply creating a new file and manually adding all of the code by hand, but that's just not as interesting, is it? To be real though, the tools that Eclipse provides are truly helpful and easy to use.

The New Java Class dialog that is displayed has many options that can be set and which will cause Eclipse to generate different code. Notice that the package name has already been supplied in the dialog because we started creating this class by right-clicking on the package name in the project. Also, the Source Folder is properly set already because you created the package inside the src folder previously.

A closer look at the code

Now, let's look at the code that was generated.

package com.rimdev.demos.tipcalc;

import net.rim.device.api.ui.UiApplication;

public class TipCalcApplication extends UiApplication {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}

The first line of code is the package declaration for com.rimdev.demos.tipcalc. This line defines the package where the TipCalcApplication class will reside. The package can be specified in the New Class dialog but because we previously added the package to the project, the package was supplied automatically to the new New Class dialog.

package com.rimdev.demos.tipcalc;

The next line is an import statement for net.rim.device.api.ui.UiApplication. Import statements are similar to .NET using or imports statements and declare which libraries are being used. The Java convention is to specifically import each class being referenced. It is possible to wildcard the import statement though, in which case the class name would be replaced with *, that is, net.rim.device.api.ui.*.

When doing this all of the classes in that package will be imported into your application and this can make coding easier. It can certainly be annoying having to go back each time you want to use a new class and add the import statement for it. Eclipse is pretty smart and shouldn't include any classes unless they are actually being used when it compiles your application, so there shouldn't be any negative impact on performance. Having said all that, the established convention is not to use wildcarding because it also makes it less clear for someone looking at your application later on to know exactly which classes are being used. In the end, it is probably best to stay with the established convention, which we will do in this article.

import net.rim.device.api.ui.UiApplication;

Next, we have the class declaration itself. Again, notice that the extends keyword is already added and the class chosen to be the superclass, UiApplication, is added as well. These are added because we chose the UiApplication to be the superclass in the New Class dialog.

public class TipCalcApplication extends UiApplication {

Lastly, notice that the public static void main method is also created. Remember that every application must have a main method, and this is that method. The method was added because we checked the checkbox for it. Very simple and easy! The words public and static are special keywords that allow the main method to be called by the system before any of the objects in your application are created.

public static void main(String[] args) {
// TODO Auto-generated method stub
}

Time for action – expanding TipCalcApplication

Now that you have the class created with some of the boilerplate code it's time to expand it and make the application actually do something.

  1. You can start off by giving the static main function something to do. Replace the main method with the following code.

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    // Create a new instance of the application.
    TipCalcApplication theApp = new TipCalcApplication();

    // To make the application enter the event thread and start
    processing messages,
    // we invoke the enterEventDispatcher() method.
    theApp.enterEventDispatcher();
    }

  2. Secondly, you need to add the TipCalcApplication constructor to the class so add the following code.
  3. private TipCalcApplication()
    {
    // Push the main screen instance onto the UI stack for
    rendering.
    pushScreen(new TipCalcMainScreen());
    }

What just happened?

The code that you just added takes the simple generated code that you got from the New Class wizard and expands it to set up and start the application.

The first thing you did was to put some code in the initially empty main method. This code in the main function is used to actually create an instance of the application's object, which happens to contain the main method. This may seem strange unless you are used to it and understand what the static keyword means. If not, then just understand that static means that the main method can be called without an instance of the object that contains it. You still do need to create an instance of the application though, and so that's the first step.

theApp = new TipCalcApplication();

The next line of code in the main method is the call to the enterEventDispatcher method on the application that you just created. This is a method already implemented in the UiApplication class. It does all of the setup necessary to get the application started, runs the application, and waits until the application is finished.

theApp.enterEventDispatcher();

As we said earlier, an Application object is required, but it's the main function that is the actual entry point of the program. When the main function is exited the application is terminated and cleaned up by the operating system. The Application object, and more specifically the call to enterEventDispatcher, is why a class derived from Application is required.

The last thing to do for this class is to create the constructor and show the first screen. We haven't created the screen yet, but we can go ahead and create the code to use it.

The constructor is also very simple and does only one thing. You could do more in the setup and initialization of things in the application constructor of course (if your application needs it), but this simple application does not. Here we create a new instance of the TipCalcMainScreen class and then push it onto the UI stack. The TipCalcMainScreen is the class that you will create next and is the screen that you will display to the user. We will come back to pushScreen and the UI Stack later.

pushScreen(new TipCalcMainScreen());

BlackBerry Java Application Development Build and deploy powerful, useful, and professional Java mobile applications for BlackBerry smartphones, the fast and easy way.
Published: July 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

(For more resources on BlackBerry, see here.)

MainScreen

A MainScreen is a specific class in the BlackBerry SDK and not just the name of our first screen. The MainScreen class provides a lot of services for you by providing a standard framework to work in. This framework helps you in the following tasks:

  • Making menus
  • Detecting a prompt for save
  • Laying out fields by providing a field manager
  • Providing a standard title bar
  • Adding standard menu items to menus

Because of this support, making your TipCalcMainScreen class derive from MainScreen is an easy choice. Again, don't let the name MainScreen box you in. Generally, every screen class that you create should be derived from MainScreen because of these features that are automatically provided.

Time for action – adding a MainScreen

Now it's time to add that screen just mentioned to your project. Adding the screen follows the same steps that you just did to add the UiApplication class.

  1. Right-click on the package and select New | Class.
  2. In the New Java Class dialog, enter TipCalcMainScreen as the class name.
  3. Select the MainScreen class to be the superclass by using the Browse button (just like we did before).
  4. Unlike last time, make sure that the public static void main (String args[]) checkbox remains unchecked.
  5. Click on Finish.

BlackBerry Java Application Development Tutorial

What just happened?

Much like before, the package declaration, the import statement, and the class definition are created automatically for you. It should look a great deal like the code generated for the TipCalcApplication class except the main method is not there. Just like before, this is just a starting point and now we need to start modifying it.

Determining your screen requirements

So, what kind of screen should this application have? Well, in order to calculate a tip, you need:

  • Some way to collect the total bill amount
  • Some way to trigger the calculation
  • Some way to display the result

There are a lot of different ways in which you can accomplish these three requirements. Laying out a screen, even a simple one such as this, is partially an art and partially a science. You could, for instance, collect the bill amount in two separate fields—one for dollars and one for cents. You might choose to use a butt on to trigger a calculation, or use a menu item to do it instead.

The topic of good UI design is well beyond the scope of this article. I will generalize and summarize development guidelines and best practices, but for those seeking a deeper look at the topic, BlackBerry provides a set of UI development guidelines at this link (http://docs.blackberry.com/en/developers/subcategories/?userType=21&category=Java+Development+Guidelines), which you can examine for all the details.

For this application, we need to make some choices and keep going even though we haven't talked about the kinds of fields available yet. To simplify things, let's just say that we will:

  • Use one edit type of field to collect the amount
  • Use a menu to trigger the calculation
  • Display the results in a dialog box

Alright, let's get to it!

Time for action – expanding the TIpCalcMainScreen

OK, so we have a plan for what we want the screen to look like. Let's start by adding the field to accept the bill amount into the application.

Add the following code to the TipCalcMainScreen class as a data member.

protected EditField amount = new EditField();

What just happened?

Talk about baby steps! This one line didn't accomplish much, but a couple of things happened that need more explanation. First, you need to know a bit more about the EditField class. It may seem obvious, but an EditField is another class in the SDK that is designed to work with the MainScreen class in order to provide standard functionality. As the name implies, an EditField is meant to allow the user to enter text data.

Secondly, as you can see in the following screenshot, EditField is underlined within Eclipse with a red squiggly line, which indicates that there is an error.

BlackBerry Java Application Development Tutorial

Hovering over the line shows a dialog with some suggestions about how to solve the problem as shown in the next screenshot:

BlackBerry Java Application Development Tutorial

In this case the editor is letting you know that the class EditField is not defined yet. The dialog offers a few suggestions about how to fix the error, such as to create a new class or interface called EditField or to go back to the project setup, in case something there is wrong. In this case, all you really need is to make sure that the class has been imported. If you select the first item in the list, Eclipse will add an import statement to your class for the EditField class. You can manually add these import statements if you wish.

BlackBerry Java Application Development Tutorial

Time for action – adding more to the MainScreen

You can continue by adding the constructor for the screen and setting up the rest of the fields. This constructor does a number of things to set up the screen. In general, it is creating and adding all of the screen elements that will be displayed.

  1. Add the following code to the TipCalcMainScreen class.

    public TipCalcMainScreen()
    {
    // Each screen can have a field in the Title section.
    LabelField title = new LabelField("TipCalc" ,
    LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
    // Set the title to the label.
    setTitle(title);
    // setup the EditField to accept the Bill Amount
    amount.setLabel("Bill Amount: $");
    // add the field to the screen
    add(amount);
    }

  2. Add the calculateTip method to the TipCalcMainScreen class.

    protected double calculateTip()
    {
    double billamount;
    // Convert the text entered into the textfield into
    // a floating point number.
    try
    {
    billamount = Double.valueOf(amount.getText().trim()).
    floatValue();
    }
    catch (NumberFormatException nfe)
    {
    billamount = 0;
    }
    double tipamount = billamount * 0.10;
    // round the computed amount to two decimal places.
    tipamount += 0.005;
    tipamount *= 100.0;
    int tip = (int)tipamount;
    tipamount = (double)tip / 100.0;
    return tipamount;
    }

What just happened?

The previous section just set up the data member variables for the screen elements but in this section you actually used them to set up the screen in the constructor. The first step is to create a field for the title portion of the MainScreen. The MainScreen class reserves a field to be displayed at the top of the screen as a title and automatically adds a line under that field. This is part of the standard look and feel of an application that you get by using the UiApplication framework and the MainScreen class.

In this case, set the title of the screen with a LabelField. Much like the EditField, a LabelField also displays text but it is intended to be a label only and therefore is not editable. The LabelField is given two style attributes as well—ELLIPSIS and USE_ALL_WIDTH. The ELLIPSIS property indicates that if the text of the LabelField is too large for the screen (remember there are many different screen sizes on the various BlackBerry handhelds), then the text will be trimmed and an ellipsis (that is, three dots in a row) is shown to indicate that it was trimmed. The USE_ALL_WIDTH property indicates that the LabelField should use as much of the screen as it is allowed.

LabelField title = new LabelField("TipCalc" ,
LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);

After creating the LabelField for the title, you need to use it by calling the setTitle method with the new LabelField object. The setTitle method is one of those methods provided by the MainScreen as part of the framework. Don't forget to add the import statement for LabelField!

setTitle(title);

The amount field was previously created as a member of the class, but there is still some setup work to do on it—specifically setting the label and adding it to the screen. Unlike some development environments, many fields include a label portion automatically. You could, of course, not set the label, in which case you would get just an empty EditField, but the label is desired so often that it was just included with the EditField and many other fields. However, not all fields have a label portion to them. For some, such as a ButtonField, it just doesn't make sense. For those fields where it does make sense, the Label is already included.

amount.setLabel("Bill Amount: $");

It should be noted that the label portion of a field is not the same as a LabelField, but is simply a portion of the EditField that is dedicated to a label function and which cannot be edited.

Once the label has been set for the amount field, the last step is to add it to the screen. This is done by using the add method. The add method is one of those framework methods which is part of the MainScreen class. Using it will add the Field object to the screen so that it can be displayed. Notice that you didn't have to use the add method for the title. Using the setTitle method does this for you under the covers.

add(amount);

Lastly, you must add the CalculateTip method —a method which is just pure Java programming and has nothing BlackBerry-specific in it, so we won't go over it line-by-line. The only line worth noting is the call to amount.getText() . Remember, amount is the name of the EditField where the user will enter the bill amount. Therefore, the getText method is used to retrieve the text that the user had entered there.

Adding a menu to the application

Menus are important user interface components on a BlackBerry. It is the preferred way to enable a user to trigger an action in an application and generally speaking, every application should have at least one.

The framework provides a great deal of support for menus and even adds some standard menu items automatically for you in proper situations. This support helps to provide a standard look and feel that makes working with your application just as easy and familiar as it is to work with any of the other standard applications.

So far, your program has a screen and a method to calculate a tip, but nothing is using that method yet. This last step sets up a menu item for your program to calculate the tip and display the results.

Time for action – adding a menu to the MainScreen

  1. Add the following code to create the menu.

    // Menu items
    MenuItem _calculateAction = new MenuItem("Calculate" , 100000, 10)
    {
    public void run()
    {
    Dialog.alert("The tip is $"+Double.toString(calculateTip()));
    }
    };

  2. Add the menu to the screen by adding the following code snippet to the class.

    protected void makeMenu(Menu menu, int instance)
    {
    menu.add(_calculateAction);
    super.makeMenu(menu, instance);
    }

What just happened?

The first step is the declaration for the menu itself. This style may look unusual if you aren't used to it. The style is a shorthand style of declaring the menu item and utilizes a technique called anonymous classes. This shorthand style contains the member declaration, creation, and inner member code for the run method, all wrapped together in one concise fragment. This technique certainly makes the coding easier to make and read, but you should understand that this is just a shortcut and that behind the scenes, the compiler is generating a lot of boilerplate code for you.

The important thing to get here is that the member_calculateAction is actually a data member of the class because this line of code is not part of a method. It MUST be done this way in order to take advantage of the shortcut. If you ignore the run method under it, this looks just like any other member declaration and creation statement.

MenuItem _calculateAction = new MenuItem(...)

In the creation of the MenuItem the text of the menu is set to Calculate and two more numbers are given to the constructor. These numbers are weighting values that tell MainScreen how to organize the menu that it is creating. The first number, 100000, is somewhat arbitrary and can just be thought of as "a big number" for this application. This is actually a sort order and a larger number will get sorted to the top of the menu. Menu items at the top of the menu should be the most commonly used functions.

new MenuItem("Calculate" , 100000, 10)

The second number is a priority. Priority is used to determine which menu item will be selected by default, and in this case, a low priority number is more likely to be selected. Lastly, the run method is also implemented. This run method is very simple, it displays the computed tip amount in a dialog. The point of all this is that when the Calculate menu item is selected, a dialog will be displayed with the tip amount. But, simply creating the menu isn't enough, we still have to add the menu item to the screen.

public void run()
{
Dialog.alert("The tip is $"+Double.toString(calculateTip()));
}

By overriding makeMenu we can add the menu items that we want to the menu, which the MainScreen is already creating. The menu being created is passed in as a parameter and we can add more menu items to it by using the add method. When the menu button is pressed the framework calls makeMenu for your application so that you can supply the menu items to be displayed. This method is called each time the menu button is pressed, so you could add different menu items to the screen depending on other situations or problems, depending on your application. In our case, we need only one menu item to calculate the tip amount.

menu.add(_calculateAction);

The second parameter to makeMenu is an instance value that lets you know what kind of menu is being created. By checking this value you can put different menu items on the diff erent menus, depending on what makes sense for your application. Generally, the full menu should have every menu item available, but the context menu (aka short menu) should have only the bare essentials and most commonly used items in it. Because we are ignoring the context value in this case, the menu will be added to each kind of menu.

If you are adding more than one menu item it doesn't matter in what order you add them. Remember, all of the ordering is done based on the "sort order" and "priority" parameters passed in when constructing the menu item objects.

The last line in the makeMenu method, super.makeMenu, is like saying "Ok, I'm done interrupting you; please continue with what you were going to do." When you override a method you get in the way of what would normally happen. Sometimes, this is desirable, such as if you don't want the normal response to happen, but sometimes it is not. super is a Java keyword meaning the superclass of your derived class. Calling the same method on super lets the superclass execute the code that it normally would execute if you hadn't overridden the method and interrupted it.

super.makeMenu(menu, instance);

Forgetting to call super.makeMenu will cause all of the menus that are added by the system automatically on your behalf to be missing!

So there you have it! At this point, the application should work, assuming you don't have any copy/paste errors. It may seem hard to believe that an application can be made with such little code. This is mostly because the framework just does so much for you and you have to concentrate only on the basics of application design.

Setting the SDK version

Early on in this article, we spent a little time to decide which version of the SDK we wanted to use. However, we haven't done anything to make that selection a reality yet. Even though the application could be compiled and executed successfully right now, we need to take a moment to make sure that we are using the right SDK version. If you've done nothing since installing Eclipse, then the SDK version is probably 4.5. We need to change the build settings to use 4.2 instead.

Time for action – selecting the right component package

Eclipse can have multiple component packages installed and each workspace is configured to use one component package. You can change the package from the Configure BlackBerry Workspace menu item on the BlackBerry menu.

  1. Navigate to BlackBerry | Configure BlackBerry Workspace. From this dialog, you can change many of the settings specific to this BlackBerry workspace. (We will come back to this part later.)
  2. Expand the BlackBerry JDE branch of the tree and select the Installed Components node. This should present a drop list with the list of installed components in it. It really doesn't matter which version you use for this sample, but this is part of choosing the version ahead of time based on which models you want to support.

    BlackBerry Java Application Development Tutorial

  3. Install JDE Component Pack v 4.2
  4. Once it is installed, make sure that the BlackBerry JDE Component Package 4.2.1 is selected in the list.
  5. When done, click on the OK button.

What just happened?

Because a workspace is tied to a specific component package, when you need to change the JDE component you will see a progress meter (like the one shown in the next screenshot) while the changes are being applied. Eclipse is actually recreating the workspace from scratch in order to properly be configured to work with the new component package.

BlackBerry Java Application Development Tutorial

Afterward, another dialog will be displayed to clean and rebuild the workspace. Any compiled output needs to be deleted because you changed the BlackBerry libraries that the project uses. Accepting the defaults will clean and rebuild all of the projects in the workspace.

BlackBerry Java Application Development Tutorial

BlackBerry Java Application Development Build and deploy powerful, useful, and professional Java mobile applications for BlackBerry smartphones, the fast and easy way.
Published: July 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

(For more resources on BlackBerry, see here.)

Testing it out

Now that we are done with the code, let's build and debug it. Because you copied all of the code there won't be any compile errors, right? Good. Eclipse is pretty good about flagging compile errors before you actually try to compile the application by placing the red squiggly line under any code with problems. At a quick glance, if you have none of these red squiggly lines in your application, then chances are good that it will compile.

Of course, just because your program will compile doesn't mean it's right and that there aren't other problems. Even simple changes like these should be tested out, which is what we will do now to make sure that the problem is really solved.

Time for action – running your new application

  • Click on Run | Debug and wait for the simulator to be displayed.

    Note that you may get warnings from your firewall or antivirus system about the simulator trying to access the Internet. There are a number of reasons why the simulator does this so don't worry about the warnings. If you do get any, acknowledge them so that you can continue.

  • Once the simulator starts, activate the TipCalc application and you can see the simple screen that you created.
  • Next, click the trackball and the "short menu" comes up.
  • Click on the Menu button or select the Full Menu menu item from the short menu to show a standard full menu.
  • Close the menu by pressing the Escape key.
  • Enter a valid value and click on the Calculate menu item.
  • Continue testing the application and see if you can spot any problems.
  • When you are ready to quit the application, close the simulator by clicking on the Close button.

What just happened?

Going through those steps should give you a good idea of how the application is used. Think back to the code you used to set up the screen and look at the screen of the application. Notice the title bar at the top and the edit field with the Bill Amount: $ label. The $ looks like it is part of the edit field, but it is really not. So, while the screen is very simple, you did get everything on the screen and it's looking good.

BlackBerry Java Application Development Tutorial

When you will open the short menu you will notice that the Calculate menu item is displayed there. Because you didn't check the instance parameter of the makeMenu method, the Calculate menu will be added to all of the menus of this application.

BlackBerry Java Application Development Tutorial

Once you open the full menu you will notice that the Calculate menu item is present and that there are a few other menu items shown as well. We didn't add these menu items. Instead, these were added by the framework automatically and is one of the reasons we are using it. The presence of these menu items adds to the standard look and feel of a BlackBerry application.

BlackBerry Java Application Development Tutorial

Now that you've explored the menus you can test out the Calculate menu item. You can see that the tip was calculated and displayed in a dialog box (just as we intended). Thanks to the nifty math in the CalculateTip method, it rounds up the value properly as well.

BlackBerry Java Application Development Tutorial

Once you quit the simulator you may notice that Eclipse is still showing the Debug perspective. If this happens it will be because you encountered an error or had a breakpoint in the code that caused the debugger to stop and switch to the Debug perspective. You can switch back to the "Workbench" perspective; click on the Java button in the upper-right corner of the screen.

BlackBerry Java Application Development Tutorial

There are quite a lot of things wrong with this application still, but in a short period of time, and with relatively little source code, you've got a basic application complete and running in the simulator. This shows the power and ease with which a basic application can be put together. As with all programs though, the little details make a big difference, and that's what we will focus on next.

Giving TipCalc some polish

Now that we have covered the basics, let's go back and give it some polish. Did you play with it enough to know what needs to be improved? Here are a few of the obvious ones that I will address.

  • There is no application icon. When you select the application on the simulator, there is a plain black window icon—a default icon supplied by the operating system if an icon is not presented.

    BlackBerry Java Application Development Tutorial

  • The name of the application is the same as the project name. This isn't horrible, but it could be better.

    BlackBerry Java Application Development Tutorial

  • The edit field on the application for the bill amount will accept any value. The bill amount needs to be limited to valid numbers.

    BlackBerry Java Application Development Tutorial

  • When exiting the application, a standard save prompt is shown. This is not useful, and is annoying, so it should be removed.

    BlackBerry Java Application Development Tutorial

So let's start going through and addressing these issues!

Adding an icon to TipCalc

Adding an icon is very easy, but choosing the right size and shape of the icon can be very confusing. Each class of device has a different screen resolution and uses diff erent sizes for the icon. Furthermore, the rules for handling icons that are not of the right size have also changed over time. We won't worry about that right now. Instead, we will just focus on adding an icon.

The icon that I made for this application is 52 x 52 pixels. Most of the icons are square-shaped and 52 pixels seems to be a pretty common size.

BlackBerry Java Application Development Tutorial

Icons can be in either GIF or PNG formats. When creating an icon be sure to use a tool that will let you specify the transparent color for the image; and no, MS Paint won't work. In this case, gray is the transparent color and the black border is not part of the image, but is displayed by the image viewer.

First, you need to add the image to the project in Eclipse. Eclipse does not have an image editor component, nor does it have the ability to add an existing file to a project. Instead, just use the Windows Explorer to copy and paste the file into the proper directory or, when creating the image using an editor, save the file directly to the project directory. What directory is that? Remember when you first launched Eclipse, it asked which directory would be used for the workspace. If you don't remember where that is you can view the project properties and the path is shown there.

Time for action – adding an icon

  1. View the project's Properties window to get to the workspace directory.

    BlackBerry Java Application Development Tutorial

    Once the Properties dialog is shown, you will find the path to the project at the top of the Resource properties page in the Location field.

  2. Using the path in the Location field, open a Windows Explorer window and browse to that location.

    BlackBerry Java Application Development Tutorial

  3. Using Windows Explorer, move the icon's image file into the project's directory in the workspace.
    Once the file is in the proper directory you may notice that it does not show up in the project list in Eclipse. Eclipse won't automatically pick it up so you need to tell Eclipse to refresh the project by selecting Refresh from the right menu or by pressing the F5 key.
  4. Refresh the Package Explorer by pressing the F5 key.

    BlackBerry Java Application Development Tutorial

  5. Once the image is listed in the project by Eclipse, open the file properties by right-clicking the image and selecting the Properties menu item. This will look similar to the project's Properties, but have only a few property pages. In this case, we want to see the BlackBerry File Properties dialog, which is done by selecting the BlackBerry File Properties group on the left-hand side of the dialog to display the BlackBerry File Properties tab on the right. There are quite a few options here, most of which are used in advanced situations, but here, the Use as application Icon checkbox is what we are after. Checking this checkbox is all there is to do; Eclipse will handle the rest. Now, when you run the application the icon will be shown instead of the default black window icon.
    BlackBerry Java Application Development Tutorial
  6. Check the Use as application icon checkbox in the BlackBerry file Properties page of the image properties dialog.

What just happened?

Setting the application icon is straightforward, once the file is in the proper place. There were a number of steps partly because we first looked up where the workspace directory is located and then even more steps because we had to copy the files into place using a Windows Explorer. Once the file was in the right place, setting the image file to be the application icon is simply a matter of checking the checkbox.

You can test this out by running the application again in the debugger and seeing that the icon is set properly. Notice that the background yellow disc shows up properly because this image file has the transparency color set properly.

BlackBerry Java Application Development Tutorial

Time for action – changing the application title

The next issue, changing the display name, is also solved by changing properties in the project's Properties dialog. In fact, there are several project settings that should be addressed at the same time!

  1. Right-click on the project name and then select the Properties menu item.
  2. Next, select the BlackBerry Project Properties from the list on the left-hand side of the screen to display the BlackBerry Project Properties tab.
    In the General tab you will find fields for several attributes, including the title and version of the application. It's a good idea to fill this dialog out as soon as you create the project.
  3. Enter the information needed for application name, vendor, and version in the dialog.
  4. Click on the OK button to close the dialog.
    Next time you compile and debug the application, the changes will be there!

BlackBerry Java Application Development Tutorial

What just happened?

Changing the title is an easy step and one that doesn't really have any effects on the application; it simply changes what is displayed on the screen when the application icon is selected.

BlackBerry Java Application Development Tutorial

Although we came to this screen just to change the title, the other values here should be given a value as well. Obviously, the system will allow the Version, Vendor, and Description fields to be empty, but it is good practice to make sure these are populated. These will be used later when you build your application for distribution. These values will show up in the BlackBerry App World or in the Application Loader when you go to install it on a device.

Fixing the Bill Amount field

The third issue is one that must be solved with code. The issue here is that the Bill Amount text box will allow any kind of text, when we really want to allow only numbers. We aren't the first to want to do this, so as you might expect, there is a way to do this already and it is called a TextFilter. A TextFilter is the base class and can support many different kinds of filters such as phone number, e-mail address, and more. A more specific class, called the NumericTextFilter , is geared toward handling numbers, so we will use that one. The EditField class knows how to interact with a TextFilter, so to add this capability is as simple as creating the filtering object and calling setFilter on the EditField.

Time for action – fixing the bill amount field

  1. Add the following code to the TipCalcMainScreen constructor.

    // In order to keep things nice and easy for the user, set a
    filter
    // preventing them from entering anything but numbers
    NumericTextFilter amt_filter = new NumericTextFilter(TextFilter.
    REAL_NUMERIC);
    amount.setFilter(amt_filter);

  2. Of course, you need to add a couple of imports to tell the compiler about the new classes that you are using. Add these as well with the other import statements at the top of the file.

    import net.rim.device.api.ui.text.TextFilter;
    import net.rim.device.api.ui.text.NumericTextFilter;

What just happened?

The NumericTextFilter needs the additional style of TextFilter.REAL_NUMERIC to let the filter know what kind of numeric is needed. Without this parameter, a decimal point would not be allowed and only whole numbers could be entered into the Bill Amount field. After creating the new filter object, we call setFilter, so that the amount field will start using it.

The result is that the amount field will now accept characters that make up only a real number.

Disabling the save prompt

The next issue to tackle is to disable the save prompt on exiting the application. Something like this is usually a good feature and the fact that it is already supported automatically by the MainScreen is a nice benefit. However, in this case it doesn't make sense and you need to stop it from happening. To do this, you need to understand how the MainScreen handles the saving feature.

The API reference shows that MainScreen offers two methods related to saving—onSavePrompt and onSave. MainScreen implements onSavePrompt for us and it is this implementation that detects if the fields have changed and then displays the dialog prompt to save.

For this application though, you won't be saving the value of the Bill Amount field, so it just doesn't make sense to display the save dialog. Fortunately, you can shortcut that logic by overriding onSavePrompt and doing nothing. By simply returning true (and not calling super.onSavePrompt), you are effectively telling the MainScreen that the user did save the data and that the application can be closed.

Time for action – disabling the "save" dialog

Add the following method to the TipCalcMainScreen class.

// return true to allow an exit without displaying the save prompt
protected boolean onSavePrompt()
{
return true;
}

What just happened?

Remember, when talking about overriding the makeMenu method that sometimes you want to call the same method of the super class (that is, super.makeMenu), and sometimes you don't. This was an example of a time when you don't want to call the super class because you wanted to interrupt what the super class was doing. In this case, simply returning true gave you the desired behavior.

Have a go hero – expanding TipCalc even more

Now that you've covered some of the basics of your first application, why not try to take it a step further and refine it even further on your own. One of the biggest problems with this application is the fact that you can calculate the tip at only one percentage. Sometimes you want to tip different amounts based on the quality of service so it can be helpful to be able to change the percentage that is used to calculate the tip.

To make this happen, add a second field to the screen where the user can change the percentage that can be used to calculate the tip. We haven't really covered any other kinds of fields so it would be best to use another EditField for now. Don't forget that the actual method for calculating the tip amount will need to be changed as well!

Summary

You just completed a couple of iterations of a real BlackBerry application, and it's a pretty good one too! The fact that you can do so little work and make such a good application speaks volumes to how powerful the BlackBerry framework is and how much it provides for you. We did gloss over many things as we sped through the article but this is just a hint of the depth and power of the development environment.

Specifically, we covered:

  • We created the project files from scratch and utilized the Eclipse New Java Class dialog to make things a bit easier
  • We created both an Application and a Screen class for the new application
  • The default properties were OK, but even this simple change improves the application tremendously
  • Every application needs an icon in the second iteration; we added one

Further resources on this subject:


About the Author :


Bill Foust

Bill has been a professional developer for over 15 years in a variety of platforms and languages. Bill first encountered a RIM 950, the predecessor to the BlackBerry brand, in 1998 and has been working with them since that time. During this early period, he wrote and sold many applications for BlackBerry through Handango.com and was involved in many custom development projects as well.
With the release of the BlackBerry 5810 in 2002, the development environment changed from C++ to Java Micro, and Bill started pursuing other opportunities, including .NET and has continued to do development and consulting professionally since then.
He wrote his first book "Mobile Guide to BlackBerry" in 2005 and later became part of the podcasting and blogging team at MobileComputingAuthority.com, which focuses on mobile devices of all kinds.

Books From Packt


Java EE 6 with GlassFish 3 Application Server
Java EE 6 with GlassFish 3 Application Server

Oracle JRockit: The Definitive Guide
Oracle JRockit: The Definitive Guide

JavaFX 1.2 Application Development Cookbook
JavaFX 1.2 Application Development Cookbook

NetBeans Platform 6.9 Developer's Guide
NetBeans Platform 6.9 Developer's Guide

BlackBerry Enterprise Server for Microsoft® Exchange
BlackBerry Enterprise Server for Microsoft® Exchange

JasperReports 3.6 Development Cookbook
JasperReports 3.6 Development Cookbook

Flash 10 Multiplayer Game Essentials
Flash 10 Multiplayer Game Essentials

FreeSWITCH 1.0.6
FreeSWITCH 1.0.6


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software