Social networking for the BlackBerry
This section examines each of the major elements of the sample application, including the relevant source-code snippets. First, a little about how the application performs and what to expect in the code.
Example social-networking application
The sample application, IBMCalendar, is a bit different from the applications in the previous parts of this series. It contains no UI screens of its own and is designed to interact directly with the BlackBerry PIM applications. That's right — there are no custom UI screens. Everything is accomplished using built-in hooks and utilities to achieve the desired functions.
A successful application must be intuitive to use or your target audience simply will not use it. Have you ever seen an application loaded with features, but you didn't actually use it because it was inconvenient to start up and access? To avoid that situation, the sample application:
- Always runs. Anytime your BlackBerry starts (not that you ever turn it off, of course) the application is started. It does not have an icon in the application ribbon.
- Installs a menu into the calendar application, making our application easy to find and always available. An effective social-networking application should be intuitive and super simple to operate.
- Presents a list of friends to connect with by using a built-in method of the
BlackBerryContactListclass. The friends are simply everyone in your contacts database.
The functions of the application are simple. Whenever an event is selected in the calendar application, you can select a custom menu to Share this Event.
Figure 3. Sharing an event
When you choose to share the event, you get a list of your friends to share the event with.
Figure 4. Choosing a friend to share event with
Once you've chosen a friend to share this event with, the application automatically sends an e-mail to the friend and drops the user back into the calendar application. The whole process takes no more than a moment. It's nonintrusive and simple to use.
Now that you know what the application looks like, it's time to look at the structure and code. To follow along by building the sample application, install the BlackBerry Java Development Environment if you haven't done so already.
The example application will be built in parts throughout the tutorial. You can download the complete source code. Figure 5 shows the source files in use in the sample application.
Figure 5. Project file in BlackBerry JDE
Because the application does not have a custom UI, there is no class dedicated to a screen (as in previous parts of this series). To start automatically without a UI, select System Module and Auto-Startup in the project's properties dialog.
Figure 6. Project settings
In the IBMCalendar.java file, look at the code in Listing 3. As in any Java application, the application requires an entry point, main, in IBMCalendar.java.
Listing 3. Main method of the IBMCalendar.java file
// IBMCalendar.java
// MSI Services, Inc.
// Frank Ableson
// 973.448.0070
// fableson@msiservices.com
// code free to use for any purpose, commercial or otherwise
package com.msi.ibm;
import net.rim.device.api.ui.*;
import net.rim.blackberry.api.menuitem.*;
// our application
class IBMCalendar extends UiApplication //implements GlobalEventListener
{
// application entry point
public static void main(String[] args)
{
System.out.println("main");
// create an instance of our app
IBMCalendar theApp = new IBMCalendar();
// "run" the app
theApp.enterEventDispatcher();
}
// app constructor
public IBMCalendar()
{
// create Menu and add it to the Calendar Application
CalendarMenus cm = new CalendarMenus(0,"Share this Event");
ApplicationMenuItemRepository.getInstance().addMenuItem
(ApplicationMenuItemRepository.MENUITEM_CALENDAR,cm);
}
}
|
The main method creates a new instance of the IBMCalendar
class, which is an extension of the UiApplication class.
UiApplication is found in the net.rim.device.api.ui
package. The UiApplication class is a base class for all
BlackBerry applications that have a UI.
The constructor of the IBMCalendar class creates an instance
of the CalendarMenus class, which is defined and
implemented in CalendarMenus.java. Once the instance of CalendarMenus is created, it is added to the calendar application
with a method in the ApplicationMenuItemRepository class.
The BlackBerry platform offers the opportunity to add menus to built-in applications. It doesn't require nasty hacks or tricky window enumerations, as is required on other platforms. This is a basic feature of the BlackBerry SDK in the net.rim.blackberry.api.menuitem package.
To add a menu to an application, you must create a class that extends the ApplicationMenuItem class. This class typically has three methods,
though ours has four to make the code a little easier to follow. The basic steps for
implementing an ApplicationMenuItem:
- Provide a constructor that may optionally allow the application to set up specific
data used by the
ApplicationMenuItem. For example, this might look like passing in a custom string value you want your custom menu to display. - The
toString()method returns the name you want displayed. This may be hard-coded or dynamically generated. - The
runmethod is invoked whenever your menu is selected. It takes a single parameter ofObjecttype. You can examine thisObjectto determine if you want to respond to this menu selection.
The CalendarMenus instance is created in Listing 4.
Listing 4:
CalendarMenus instanceCalendarMenus cm = new CalendarMenus(0,"Share this Event"); |
The menu text for this instance, "Share this Event," can be whatever string value you want, though, obviously, you must make sure it's compact and intuitive. Implementation of these methods in Listing 5 shows the code from CalendarMenus.java. We will review the major elements of this file one by one.
Listing 5. CalendarMenus.java
//CalendarMenus.java
// MSI Services, Inc.
// Frank Ableson
// 973.448.0070
// fableson@msiservices.com
// code free to use for any purpose, commercial or otherwise
package com.msi.ibm;
import net.rim.blackberry.api.mail.*;
import net.rim.blackberry.api.mail.event.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.blackberry.api.menuitem.*;
import java.util.Enumeration;
import javax.microedition.pim.Event;
import net.rim.blackberry.api.pdap.BlackBerryEvent;
import javax.microedition.pim.*;
import java.util.Enumeration;
import net.rim.blackberry.api.pdap.*;
class CalendarMenus extends ApplicationMenuItem
{
String myname;
CalendarMenus(int order,String name)
{
super(order);
myname = name;
}
//Run is called when the menuItem is invoked
public Object run(Object context)
{
//context object should be an Event
if (context instanceof Event)
{
try
{
Event evt = (Event) context;
System.out.println("Handling our Calendar Option");
java.lang.String s;
handleCalendarEvent(evt);
}
catch (Exception ex)
{
System.out.println(ex);
ex.printStackTrace();
}
}
return context;
}
//toString should return the string we want to
//use as the test for the menuItem
public String toString(){
return myname;
}
public void handleCalendarEvent(Event e)
{
System.out.println("handling Calendar Event [" + e.toString() + "]");
try
{
net.rim.blackberry.api.pdap.BlackBerryContactList contactList =
(BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST,PIM.READ_ONLY);
Contact c = contactList.choose(null,BlackBerryContactList.
AddressTypes.EMAIL,false);
if (c == null)
{
System.out.println("no contact chosen, bail");
}
else
{
String emailAddress = c.getString(Contact.EMAIL,0);
System.out.println(emailAddress);
String eventData = "You're Invited!\n";
eventData += "What: " + e.getString(Event.SUMMARY,0) + "\n";
eventData += "Where: " + e.getString(Event.LOCATION,0) + "\n";
eventData += "When: " + new java.util.Date(e.getDate(Event.START,0)).
toString() + " until " + new java.util.Date(e.getDate(Event.END,0)).toString() + "\n";
System.out.println(eventData);
SendEmail se = new SendEmail(emailAddress,eventData);
se.start();
}
}
catch (Exception ee)
{
System.err.println(ee.getMessage());
ee.printStackTrace();
}
}
}
|
There are a handful of method calls to System.out.println.
This is used for debugging purposes, as it's helpful to see a trace of the methods
being invoked. This technique is even more helpful in an application that does not
have a UI. To see this data in the BlackBerry JDE, view the Output
window, which you can access under the View menu or by the key-combination of Alt+2 in the JDE.
Starting with the constructor, notice that a parameter is passed in the order you
desire the menu to appear. The example uses zero, which places the menu all the way
to the top, as seen in Figure 3. This value is passed to the
super class. The other parameter used in this constructor is a string value that
contains a name for the menu. This value is stored in the member variable myname. At this point, the constructor has done its job and this instance of the CalendarMenus class is ready.
Back in Listing 2, this class is instantiated and employed in the
constructor of the IBMCalendar class. Once the class is
instantiated, it must be added to the application menu of choice, which is
accomplished through the ApplicationMenuItemRepository
class. The code gets an instance of this class from the static getInstance method. The addMenuItem
method takes two arguments:
- The location where this menu should be added
- An instance of the
CalendarMenu
The ApplicationMenuItemRepository offers several possible
locations where the menu may be installed, which equates to virtually all of the
built-in applications. The RIM Java API Library documentation has a complete reference of the available menu locations.
When the menu is selected, the run method of the CalendarMenus class is invoked. The lone argument to this method is of type Object. This is interrogated at run time and, if it is found to be of type Event, the code processes it. In this case, the event is processed by passing it to the method handleCalendarEvent. The handleCalendarEvent method performs three main steps:
- Asks the user to choose a contact. To do this, the PIM database is accessed and the
default contacts list is opened. Once the
PIMListis opened, the choose method is invoked. This method initiates a "search user interface" where the user can select a contact. The second argument,BlackBerryContactList.AddressTypes.EMAIL, instructs the choose method to show contacts with e-mail addresses. If no contact is chosen, the application simply takes no further action. - Once a contact is chosen, the event data is extracted and formatted into a simple
"What, Where, When" human-readable format. The "date" values are used as
arguments to anonymous instances of
java.util.Date. The e-mail address is extracted from theContactinstance. - Equipped with an e-mail address and a formatted body of text, the next step is to send an e-mail.
The final step for the social-networking application is the sending of a simple e-mail
to a friend to share an Event of interest. To do this, the sample application implements a class
named SendEmail, found in SendEmail.java.
Listing 6. Sending the e-mail
// SendEmail.java
// MSI Services, Inc.
// Frank Ableson
// 973.448.0070
// fableson@msiservices.com
// code free to use for any purpose, commercial or otherwise
package com.msi.ibm;
import net.rim.blackberry.api.mail.event.*;
import net.rim.blackberry.api.mail.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.component.Dialog;
/**
*
*/
class SendEmail extends Thread
{
boolean bCanSend = false;
Store msgStore;
Folder[] folderList;
Folder outFolder;
Message msg;
Transport emailTransport;
String _emailTo,_emailBody;
SendEmail(String emailTo,String emailBody)
{
try
{
Session s = Session.getDefaultInstance();
if(s == null)
{
String errMsg = "Unabled to send email message.\n";
Dialog.alert(errMsg);
bCanSend = false;
}
else
{
bCanSend = true;
_emailTo = emailTo;
_emailBody = emailBody;
emailTransport = Session.waitForDefaultSession().getTransport();
msgStore = Session.waitForDefaultSession().getStore();
folderList = msgStore.list(Folder.SENT);
outFolder = folderList[0];
msg = new Message(outFolder);
}
}
catch(NoSuchServiceException nse)
{
nse.toString();
}
}
public void run()
{
System.out.println("SendEmail :: running");
if(bCanSend == true)
{
try
{
Address [] addresses = new Address[1];
addresses[0] = new Address(_emailTo, _emailTo);
msg.addRecipients(Message.RecipientType.TO, addresses);
msg.setSubject("IBM Calendar Share!");
msg.setContent(_emailBody);
emailTransport.send(msg);
}
catch(Exception e)
{
System.out.println("Exception caught trying to send email: " +
e.toString());
}
}
}
}
|
SendEmail extends java.util.Thread. You want the task of sending an e-mail to take
place independent of any UI thread. The class is instantiated by a
constructor that takes two arguments — the e-mail recipient and the formatted
message. The constructor attempts to do some initialization work by:
- Connecting to the communications subsystem of the BlackBerry device.
- Getting a reference to the outbox.
- Creating a new e-mail message, of class type
Message, within the outbox.
When the class is started, the message is addressed and the body of the e-mail is set up and sent.
You have reviewed all of the important code snippets and it's time to build and test the application. Assuming the application has been built without errors, it's time to run it in the BlackBerry simulator.
- Make sure that the MDS simulator is running. The MDS simulator allows the BlackBerry simulator to connect to the network, including the Internet.
- Select F5 to start the BlackBerry simulator. The tutorial sample application starts right away in the background.
- To test the application, make sure your device has some contact entries and an event entry. While the event is highlighted in the calendar application, select the Share this Event menu.
- Choose a contact. With any luck, your friend will receive a simple and friendly
e-mail inviting them to join you. Figure 7 shows the e-mail invitation.
Figure 7. A shared event
- But wait. Does your BlackBerry already have a feature called Invite Attendee? Go ahead, try it out. The recipient receives an "ics" file, which is a standard format for a meeting invitation. Unless your mail client is equipped to process that ics file, it comes across as a bunch of noninteresting text.
The social-networking application provides a starting point for more creative applications that you will write. Instead of sending an e-mail, it could make an entry to a blog, for example. The only limitation at this point is your imagination.





