Let's add some real functionality to the application. We're going to use the PIM API from JSR-75 to access and display contacts from the device. Add a List and a PIM to the MIDlet's member variables:
... import com.sun.lwuit.List; import javax.microedition.pim.PIM; public class Midlet extends MIDlet { private List contactList = null; private PIM pim = null; ...
Next, add code to startApp()
to initialize the
GUI and populate the contact list:
import com.sun.lwuit.TextArea; import com.sun.lwuit.TextField; import com.sun.lwuit.events.ActionListener; import com.sun.lwuit.layouts.BoxLayout; import.com.sun.lwuit.Button; ... public void startApp() { ... form.setLayout(new BoxLayout(BoxLayout.Y_AXIS)); contactList = new List(); form.addComponent(contactList); pim = PIM.getInstance(); final TextArea searchField = TextField.create(); form.addComponent(searchField); Button searchButton = new Button("Search"); form.addComponent(searchButton); searchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { populateContactList(searchField.getText()); } }); populateContactList(searchField.getText()); form.show(); form.setFocused(searchField); ... }
We add two more UI components here: a search field and a button.
Note that the TextArea
is marked final because
we want to use it in the Button's event handler. We use the contents
of the TextArea
as input to the populateContactList()
method, which will filter the contacts by that string. The button
gets an ActionListener
instance to handle clicks,
but we could also assign a Command
to the button
to take care of the events.
Here is the code for populateContactList()
:
import com.sun.lwuit.list.DefaultListModel; import java.util.Enumeration; import javax.microedition.pim.Contact; import javax.microedition.pim.ContactList; import javax.microedition.pim.PIM; import javax.microedition.pim.PIMException; ... public void startApp() { ... } private void populateContactList(String searchTerm) { contactList.setModel(new DefaultListModel()); try { String[] pimListNames = pim.listPIMLists(PIM.CONTACT_LIST); for (int i = 0; i < pimListNames.length; ++i) { ContactList cl = (ContactList) pim.openPIMList( PIM.CONTACT_LIST, PIM.READ_ONLY, pimListNames[i]); Enumeration items = cl.items(searchTerm); while (items.hasMoreElements()) { Contact c = (Contact) items.nextElement(); contactList.addItem(c.getString(Contact.FORMATTED_NAME, 0)); } } } catch (PIMException ex) { ex.printStackTrace(); } if (contactList.getModel().getSize() == 0) { contactList.addItem("No matches"); } }
Whenever we repopulate the contact list, the first thing to do is to clear the list. This is done by setting an empty model. Next, we access the contacts list or lists - phones often have more than one contacts list, for example one on the phone itself and one on the SIM card. That's why we get the names of all the contacts lists and then iterate over all the lists, adding each item's formatted name to our list widget.