Skip to content

Listening to address book changes in your BlackBerry app.

Your BlackBerry application needs to know when the user adds, removes, or changes something in the BlackBerry address book. So, how would you go about implementing this?

Here is a simple class that will listen to changes in the BlackBerry address book:

import java.util.Enumeration;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIMItem;
import javax.microedition.pim.PIMList;
import net.rim.blackberry.api.pdap.PIMListListener2;

final class MyPIMListener implements PIMListListener2
{
    public void itemAdded ( PIMItem item )
    {
        if ( item == null )
        {
            return;
        }

        Contact contact = (Contact)item;
        // ...
    }

    public void itemRemoved ( PIMItem item )
    {
        if ( item == null )
        {
            return;
        }

        Contact contact = (Contact)item;
        // ...
    }

    public void itemUpdated ( PIMItem oldItem, PIMItem newItem )
    {
        if ( oldItem == null || newItem == null )
        {
            return;
        }

        itemRemoved(oldItem);
        itemAdded(newItem);
    }

    public void batchOperation ( PIMList list )
    {
        if ( list == null )
        {
            return;
        }

        try
        {
            ContactList contactList = (ContactList)list;
            Enumeration e = contactList.items();

            while ( e.hasMoreElements() )
            {
                Contact contact = (Contact)e.nextElement();
                // ...
            }
        }
        catch ( Exception e )
        {
            // ...
        }
    }
}

To use the above class, you need to add an instance of it as a listener to the BlackBerry contact list. Here is how you would do that.

MyPIMListener listener = new MyPIMListener();
ContactList contactList = (ContactList)PIM.getInstance().openPIMList(
    PIM.CONTACT_LIST, PIM_READ_ONLY);

BlackBerryPIMList blackberryContactList = (BlackBerryPIMList)contactList;
blackberryContactList.addListener(listener);