Monday, May 6, 2013

View contact list using j2me


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package the.contact.space;

import java.util.Enumeration;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMList;

/**
 * @author User
 */
public class ViewContactList extends Form implements CommandListener {
    private final Home midlet;
    private Command cmdBack;
    private Enumeration contacts;
    private List contactList;
    private ContactList contList;

    /**
     *
     */
    public ViewContactList(String title, Home midlet) {
        super(title);
        this.midlet = midlet;
        cmdBack = new Command("Back", Command.BACK, 1);
        addCommand(cmdBack);
        setCommandListener(this);
        contactList = new List("Contact List", List.IMPLICIT);
        viewContactList2();
    }
    
    private void viewContactList2() {
        try {
            PIM pimInst = PIM.getInstance();
            contList = (ContactList) pimInst.openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
            contacts = contList.items();
            while (contacts.hasMoreElements()) {
                Contact tCont = (Contact) contacts.nextElement();
                String[] nameValues = tCont.getStringArray(Contact.NAME, 0);
                String firstName = nameValues[Contact.NAME_GIVEN];
                String lastName = nameValues[Contact.NAME_FAMILY];
                String phone = tCont.getString(Contact.TEL, 0);
                String email = null;
                try {
                    email = tCont.getString(Contact.EMAIL, 0);
                } catch (Exception ex) {}
                contactList.append(firstName + " " + lastName + "\n" + phone, null);
            }
            contactList.addCommand(cmdBack);
            contactList.setCommandListener(this);
            this.midlet.getDisplay().setCurrent(contactList);
        } catch (Exception ex) {
            ex.printStackTrace();
            Alert error = new Alert("Error", "No available contacts."+ex.getMessage(), null, AlertType.ERROR);
            error.setTimeout(Alert.FOREVER);
            this.midlet.getDisplay().setCurrent(error);
            return;
        }
    }
    
    public void commandAction(Command c, Displayable d) {
        if (c == cmdBack) {
            midlet.displayMainMIDlet();
        }
    }
}

No comments:

Post a Comment